1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | "use strict";
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | module.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 |
|
30 |
|
31 |
|
32 |
|
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 | };
|