UNPKG

1.74 kBJavaScriptView Raw
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
13module.exports = {
14 meta: {
15 docs: {
16 description: "disallow comparisons where both sides are exactly the same",
17 category: "Best Practices",
18 recommended: false,
19 url: "https://eslint.org/docs/rules/no-self-compare"
20 },
21
22 schema: []
23 },
24
25 create(context) {
26 const sourceCode = context.getSourceCode();
27
28 /**
29 * Determines whether two nodes are composed of the same tokens.
30 * @param {ASTNode} nodeA The first node
31 * @param {ASTNode} nodeB The second node
32 * @returns {boolean} true if the nodes have identical token representations
33 */
34 function hasSameTokens(nodeA, nodeB) {
35 const tokensA = sourceCode.getTokens(nodeA);
36 const tokensB = sourceCode.getTokens(nodeB);
37
38 return tokensA.length === tokensB.length &&
39 tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value);
40 }
41
42 return {
43
44 BinaryExpression(node) {
45 const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]);
46
47 if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) {
48 context.report({ node, message: "Comparing to itself is potentially pointless." });
49 }
50 }
51 };
52
53 }
54};