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 | docs: {
|
14 | description: "disallow comparing against -0",
|
15 | category: "Possible Errors",
|
16 | recommended: true,
|
17 | url: "https://eslint.org/docs/rules/no-compare-neg-zero"
|
18 | },
|
19 | fixable: null,
|
20 | schema: [],
|
21 | messages: {
|
22 | unexpected: "Do not use the '{{operator}}' operator to compare against -0."
|
23 | }
|
24 | },
|
25 |
|
26 | create(context) {
|
27 |
|
28 | //--------------------------------------------------------------------------
|
29 | // Helpers
|
30 | //--------------------------------------------------------------------------
|
31 |
|
32 | /**
|
33 | * Checks a given node is -0
|
34 | *
|
35 | * @param {ASTNode} node - A node to check.
|
36 | * @returns {boolean} `true` if the node is -0.
|
37 | */
|
38 | function isNegZero(node) {
|
39 | return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0;
|
40 | }
|
41 | const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]);
|
42 |
|
43 | return {
|
44 | BinaryExpression(node) {
|
45 | if (OPERATORS_TO_CHECK.has(node.operator)) {
|
46 | if (isNegZero(node.left) || isNegZero(node.right)) {
|
47 | context.report({
|
48 | node,
|
49 | messageId: "unexpected",
|
50 | data: { operator: node.operator }
|
51 | });
|
52 | }
|
53 | }
|
54 | }
|
55 | };
|
56 | }
|
57 | };
|