/node_modules/eslint/lib/rules/no-confusing-arrow.js

https://bitbucket.org/egorBugaev/hw59_part2 · JavaScript · 76 lines · 41 code · 13 blank · 22 comment · 6 complexity · e09880fc1e4cc9e43d5b90f2750cd7d7 MD5 · raw file

  1. /**
  2. * @fileoverview A rule to warn against using arrow functions when they could be
  3. * confused with comparisions
  4. * @author Jxck <https://github.com/Jxck>
  5. */
  6. "use strict";
  7. const astUtils = require("../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. docs: {
  25. description: "disallow arrow functions where they could be confused with comparisons",
  26. category: "ECMAScript 6",
  27. recommended: false
  28. },
  29. fixable: "code",
  30. schema: [{
  31. type: "object",
  32. properties: {
  33. allowParens: { type: "boolean" }
  34. },
  35. additionalProperties: false
  36. }]
  37. },
  38. create(context) {
  39. const config = context.options[0] || {};
  40. const sourceCode = context.getSourceCode();
  41. /**
  42. * Reports if an arrow function contains an ambiguous conditional.
  43. * @param {ASTNode} node - A node to check and report.
  44. * @returns {void}
  45. */
  46. function checkArrowFunc(node) {
  47. const body = node.body;
  48. if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) {
  49. context.report({
  50. node,
  51. message: "Arrow function used ambiguously with a conditional expression.",
  52. fix(fixer) {
  53. // if `allowParens` is not set to true dont bother wrapping in parens
  54. return config.allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
  55. }
  56. });
  57. }
  58. }
  59. return {
  60. ArrowFunctionExpression: checkArrowFunc
  61. };
  62. }
  63. };