Blame view

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