no-self-compare.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. /** @type {import('../types').Rule.RuleModule} */
  11. module.exports = {
  12. meta: {
  13. type: "problem",
  14. docs: {
  15. description:
  16. "Disallow comparisons where both sides are exactly the same",
  17. recommended: false,
  18. url: "https://eslint.org/docs/latest/rules/no-self-compare",
  19. },
  20. schema: [],
  21. messages: {
  22. comparingToSelf: "Comparing to itself is potentially pointless.",
  23. },
  24. },
  25. create(context) {
  26. const sourceCode = context.sourceCode;
  27. /**
  28. * Determines whether two nodes are composed of the same tokens.
  29. * @param {ASTNode} nodeA The first node
  30. * @param {ASTNode} nodeB The second node
  31. * @returns {boolean} true if the nodes have identical token representations
  32. */
  33. function hasSameTokens(nodeA, nodeB) {
  34. const tokensA = sourceCode.getTokens(nodeA);
  35. const tokensB = sourceCode.getTokens(nodeB);
  36. return (
  37. tokensA.length === tokensB.length &&
  38. tokensA.every(
  39. (token, index) =>
  40. token.type === tokensB[index].type &&
  41. token.value === tokensB[index].value,
  42. )
  43. );
  44. }
  45. return {
  46. BinaryExpression(node) {
  47. const operators = new Set([
  48. "===",
  49. "==",
  50. "!==",
  51. "!=",
  52. ">",
  53. "<",
  54. ">=",
  55. "<=",
  56. ]);
  57. if (
  58. operators.has(node.operator) &&
  59. hasSameTokens(node.left, node.right)
  60. ) {
  61. context.report({ node, messageId: "comparingToSelf" });
  62. }
  63. },
  64. };
  65. },
  66. };