1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | "use strict";
|
8 |
|
9 |
|
10 |
|
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 | category: "Best Practices",
|
20 | recommended: false,
|
21 | url: "https://eslint.org/docs/rules/no-self-compare"
|
22 | },
|
23 |
|
24 | schema: [],
|
25 |
|
26 | messages: {
|
27 | comparingToSelf: "Comparing to itself is potentially pointless."
|
28 | }
|
29 | },
|
30 |
|
31 | create(context) {
|
32 | const sourceCode = context.getSourceCode();
|
33 |
|
34 | |
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | function hasSameTokens(nodeA, nodeB) {
|
41 | const tokensA = sourceCode.getTokens(nodeA);
|
42 | const tokensB = sourceCode.getTokens(nodeB);
|
43 |
|
44 | return tokensA.length === tokensB.length &&
|
45 | tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value);
|
46 | }
|
47 |
|
48 | return {
|
49 |
|
50 | BinaryExpression(node) {
|
51 | const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]);
|
52 |
|
53 | if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) {
|
54 | context.report({ node, messageId: "comparingToSelf" });
|
55 | }
|
56 | }
|
57 | };
|
58 |
|
59 | }
|
60 | };
|