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