no-compare-neg-zero.js 1.9 KB

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