no-compare-neg-zero.js 1.6 KB

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