use-includes-instead-of-indexOf.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * @fileoverview Use .includes instead of .indexOf
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. */
  8. "use strict";
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. url:
  13. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/use-includes-instead-of-indexOf.html",
  14. },
  15. type: "suggestion",
  16. },
  17. create(context) {
  18. return {
  19. BinaryExpression(node) {
  20. if (
  21. node.left.type != "CallExpression" ||
  22. node.left.callee.type != "MemberExpression" ||
  23. node.left.callee.property.type != "Identifier" ||
  24. node.left.callee.property.name != "indexOf"
  25. ) {
  26. return;
  27. }
  28. if (
  29. (["!=", "!==", "==", "==="].includes(node.operator) &&
  30. node.right.type == "UnaryExpression" &&
  31. node.right.operator == "-" &&
  32. node.right.argument.type == "Literal" &&
  33. node.right.argument.value == 1) ||
  34. ([">=", "<"].includes(node.operator) &&
  35. node.right.type == "Literal" &&
  36. node.right.value == 0)
  37. ) {
  38. context.report(node, "use .includes instead of .indexOf");
  39. }
  40. },
  41. };
  42. },
  43. };