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