]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-confusing-arrow.js
import 8.3.0 source
[pve-eslint.git] / eslint / lib / rules / no-confusing-arrow.js
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
7 "use strict";
8
9 const astUtils = require("./utils/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 type: "suggestion",
31
32 docs: {
33 description: "disallow arrow functions where they could be confused with comparisons",
34 recommended: false,
35 url: "https://eslint.org/docs/rules/no-confusing-arrow"
36 },
37
38 fixable: "code",
39
40 schema: [{
41 type: "object",
42 properties: {
43 allowParens: { type: "boolean", default: true }
44 },
45 additionalProperties: false
46 }],
47
48 messages: {
49 confusing: "Arrow function used ambiguously with a conditional expression."
50 }
51 },
52
53 create(context) {
54 const config = context.options[0] || {};
55 const allowParens = config.allowParens || (config.allowParens === void 0);
56 const sourceCode = context.getSourceCode();
57
58
59 /**
60 * Reports if an arrow function contains an ambiguous conditional.
61 * @param {ASTNode} node A node to check and report.
62 * @returns {void}
63 */
64 function checkArrowFunc(node) {
65 const body = node.body;
66
67 if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
68 context.report({
69 node,
70 messageId: "confusing",
71 fix(fixer) {
72
73 // if `allowParens` is not set to true don't bother wrapping in parens
74 return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
75 }
76 });
77 }
78 }
79
80 return {
81 ArrowFunctionExpression: checkArrowFunc
82 };
83 }
84 };