1 | /**
|
2 | * @fileoverview The rule should warn against code that tries to compare against -0.
|
3 | * @author Aladdin-ADD <hh_2013@foxmail.com>
|
4 | */
|
5 | ;
|
6 |
|
7 | //------------------------------------------------------------------------------
|
8 | // Rule Definition
|
9 | //------------------------------------------------------------------------------
|
10 |
|
11 | module.exports = {
|
12 | meta: {
|
13 | type: "problem",
|
14 |
|
15 | docs: {
|
16 | description: "disallow comparing against -0",
|
17 | category: "Possible Errors",
|
18 | recommended: true,
|
19 | url: "https://eslint.org/docs/rules/no-compare-neg-zero"
|
20 | },
|
21 |
|
22 | fixable: null,
|
23 | schema: [],
|
24 |
|
25 | messages: {
|
26 | unexpected: "Do not use the '{{operator}}' operator to compare against -0."
|
27 | }
|
28 | },
|
29 |
|
30 | create(context) {
|
31 |
|
32 | //--------------------------------------------------------------------------
|
33 | // Helpers
|
34 | //--------------------------------------------------------------------------
|
35 |
|
36 | /**
|
37 | * Checks a given node is -0
|
38 | * @param {ASTNode} node A node to check.
|
39 | * @returns {boolean} `true` if the node is -0.
|
40 | */
|
41 | function isNegZero(node) {
|
42 | return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0;
|
43 | }
|
44 | const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]);
|
45 |
|
46 | return {
|
47 | BinaryExpression(node) {
|
48 | if (OPERATORS_TO_CHECK.has(node.operator)) {
|
49 | if (isNegZero(node.left) || isNegZero(node.right)) {
|
50 | context.report({
|
51 | node,
|
52 | messageId: "unexpected",
|
53 | data: { operator: node.operator }
|
54 | });
|
55 | }
|
56 | }
|
57 | }
|
58 | };
|
59 | }
|
60 | };
|