UNPKG

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