UNPKG

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