no-confusing-arrow.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @fileoverview A rule to warn against using arrow functions when they could be
  3. * confused with comparisons
  4. * @author Jxck <https://github.com/Jxck>
  5. */
  6. "use strict";
  7. const astUtils = require("./utils/ast-utils.js");
  8. //------------------------------------------------------------------------------
  9. // Helpers
  10. //------------------------------------------------------------------------------
  11. /**
  12. * Checks whether or not a node is a conditional expression.
  13. * @param {ASTNode} node node to test
  14. * @returns {boolean} `true` if the node is a conditional expression.
  15. */
  16. function isConditional(node) {
  17. return node && node.type === "ConditionalExpression";
  18. }
  19. //------------------------------------------------------------------------------
  20. // Rule Definition
  21. //------------------------------------------------------------------------------
  22. module.exports = {
  23. meta: {
  24. type: "suggestion",
  25. docs: {
  26. description: "disallow arrow functions where they could be confused with comparisons",
  27. category: "ECMAScript 6",
  28. recommended: false,
  29. url: "https://eslint.org/docs/rules/no-confusing-arrow"
  30. },
  31. fixable: "code",
  32. schema: [{
  33. type: "object",
  34. properties: {
  35. allowParens: { type: "boolean", default: true }
  36. },
  37. additionalProperties: false
  38. }],
  39. messages: {
  40. confusing: "Arrow function used ambiguously with a conditional expression."
  41. }
  42. },
  43. create(context) {
  44. const config = context.options[0] || {};
  45. const allowParens = config.allowParens || (config.allowParens === void 0);
  46. const sourceCode = context.getSourceCode();
  47. /**
  48. * Reports if an arrow function contains an ambiguous conditional.
  49. * @param {ASTNode} node A node to check and report.
  50. * @returns {void}
  51. */
  52. function checkArrowFunc(node) {
  53. const body = node.body;
  54. if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
  55. context.report({
  56. node,
  57. messageId: "confusing",
  58. fix(fixer) {
  59. // if `allowParens` is not set to true don't bother wrapping in parens
  60. return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
  61. }
  62. });
  63. }
  64. }
  65. return {
  66. ArrowFunctionExpression: checkArrowFunc
  67. };
  68. }
  69. };