Ohm-Management - Projektarbeit B-ME
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.

no-self-compare.js 1.7KB

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