项目原始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.
 
 
 
 

55 lines
1.7 KiB

  1. /**
  2. * @fileoverview Rule to flag comparison where left part is the same as the right
  3. * part.
  4. * @author Ilya Volodin
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description: "disallow comparisons where both sides are exactly the same",
  14. category: "Best Practices",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/no-self-compare"
  17. },
  18. schema: []
  19. },
  20. create(context) {
  21. const sourceCode = context.getSourceCode();
  22. /**
  23. * Determines whether two nodes are composed of the same tokens.
  24. * @param {ASTNode} nodeA The first node
  25. * @param {ASTNode} nodeB The second node
  26. * @returns {boolean} true if the nodes have identical token representations
  27. */
  28. function hasSameTokens(nodeA, nodeB) {
  29. const tokensA = sourceCode.getTokens(nodeA);
  30. const tokensB = sourceCode.getTokens(nodeB);
  31. return tokensA.length === tokensB.length &&
  32. tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value);
  33. }
  34. return {
  35. BinaryExpression(node) {
  36. const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]);
  37. if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) {
  38. context.report({ node, message: "Comparing to itself is potentially pointless." });
  39. }
  40. }
  41. };
  42. }
  43. };