]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-self-compare.js
import 8.3.0 source
[pve-eslint.git] / eslint / lib / rules / no-self-compare.js
1 /**
2 * @fileoverview Rule to flag comparison where left part is the same as the right
3 * part.
4 * @author Ilya Volodin
5 */
6
7 "use strict";
8
9 //------------------------------------------------------------------------------
10 // Rule Definition
11 //------------------------------------------------------------------------------
12
13 module.exports = {
14 meta: {
15 type: "problem",
16
17 docs: {
18 description: "disallow comparisons where both sides are exactly the same",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/no-self-compare"
21 },
22
23 schema: [],
24
25 messages: {
26 comparingToSelf: "Comparing to itself is potentially pointless."
27 }
28 },
29
30 create(context) {
31 const sourceCode = context.getSourceCode();
32
33 /**
34 * Determines whether two nodes are composed of the same tokens.
35 * @param {ASTNode} nodeA The first node
36 * @param {ASTNode} nodeB The second node
37 * @returns {boolean} true if the nodes have identical token representations
38 */
39 function hasSameTokens(nodeA, nodeB) {
40 const tokensA = sourceCode.getTokens(nodeA);
41 const tokensB = sourceCode.getTokens(nodeB);
42
43 return tokensA.length === tokensB.length &&
44 tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value);
45 }
46
47 return {
48
49 BinaryExpression(node) {
50 const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]);
51
52 if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) {
53 context.report({ node, messageId: "comparingToSelf" });
54 }
55 }
56 };
57
58 }
59 };