UNPKG

1.99 kBJavaScriptView Raw
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"use strict";
8
9const 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 */
20function isConditional(node) {
21 return node && node.type === "ConditionalExpression";
22}
23
24//------------------------------------------------------------------------------
25// Rule Definition
26//------------------------------------------------------------------------------
27
28module.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 },
35
36 schema: [{
37 type: "object",
38 properties: {
39 allowParens: {type: "boolean"}
40 },
41 additionalProperties: false
42 }]
43 },
44
45 create(context) {
46 const config = context.options[0] || {};
47 const sourceCode = context.getSourceCode();
48
49 /**
50 * Reports if an arrow function contains an ambiguous conditional.
51 * @param {ASTNode} node - A node to check and report.
52 * @returns {void}
53 */
54 function checkArrowFunc(node) {
55 const body = node.body;
56
57 if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) {
58 context.report(node, "Arrow function used ambiguously with a conditional expression.");
59 }
60 }
61
62 return {
63 ArrowFunctionExpression: checkArrowFunc
64 };
65 }
66};