UNPKG

1.94 kBJavaScriptView Raw
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"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.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 *
39 * @param {ASTNode} node - A node to check.
40 * @returns {boolean} `true` if the node is -0.
41 */
42 function isNegZero(node) {
43 return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0;
44 }
45 const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]);
46
47 return {
48 BinaryExpression(node) {
49 if (OPERATORS_TO_CHECK.has(node.operator)) {
50 if (isNegZero(node.left) || isNegZero(node.right)) {
51 context.report({
52 node,
53 messageId: "unexpected",
54 data: { operator: node.operator }
55 });
56 }
57 }
58 }
59 };
60 }
61};