项目原始demo,不改动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 

58 lines
1.9 KiB

  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. module.exports = {
  10. meta: {
  11. docs: {
  12. description: "disallow comparing against -0",
  13. category: "Possible Errors",
  14. recommended: true,
  15. url: "https://eslint.org/docs/rules/no-compare-neg-zero"
  16. },
  17. fixable: null,
  18. schema: [],
  19. messages: {
  20. unexpected: "Do not use the '{{operator}}' operator to compare against -0."
  21. }
  22. },
  23. create(context) {
  24. //--------------------------------------------------------------------------
  25. // Helpers
  26. //--------------------------------------------------------------------------
  27. /**
  28. * Checks a given node is -0
  29. *
  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. };