github-pages-deploy-action/node_modules/eslint/lib/rules/no-confusing-arrow.js

86 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview A rule to warn against using arrow functions when they could be
2020-05-15 05:33:08 +08:00
* confused with comparisons
2020-03-07 11:45:40 +08:00
* @author Jxck <https://github.com/Jxck>
*/
"use strict";
2020-03-31 20:40:00 +08:00
const astUtils = require("./utils/ast-utils.js");
2020-03-07 11:45:40 +08:00
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a node is a conditional expression.
2020-03-31 20:40:00 +08:00
* @param {ASTNode} node node to test
2020-03-07 11:45:40 +08:00
* @returns {boolean} `true` if the node is a conditional expression.
*/
function isConditional(node) {
return node && node.type === "ConditionalExpression";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow arrow functions where they could be confused with comparisons",
category: "ECMAScript 6",
recommended: false,
url: "https://eslint.org/docs/rules/no-confusing-arrow"
},
fixable: "code",
schema: [{
type: "object",
properties: {
2020-03-31 20:40:00 +08:00
allowParens: { type: "boolean", default: true }
2020-03-07 11:45:40 +08:00
},
additionalProperties: false
}],
messages: {
confusing: "Arrow function used ambiguously with a conditional expression."
}
},
create(context) {
const config = context.options[0] || {};
2020-03-31 20:40:00 +08:00
const allowParens = config.allowParens || (config.allowParens === void 0);
2020-03-07 11:45:40 +08:00
const sourceCode = context.getSourceCode();
2020-03-31 20:40:00 +08:00
2020-03-07 11:45:40 +08:00
/**
* Reports if an arrow function contains an ambiguous conditional.
2020-03-31 20:40:00 +08:00
* @param {ASTNode} node A node to check and report.
2020-03-07 11:45:40 +08:00
* @returns {void}
*/
function checkArrowFunc(node) {
const body = node.body;
2020-03-31 20:40:00 +08:00
if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
2020-03-07 11:45:40 +08:00
context.report({
node,
messageId: "confusing",
fix(fixer) {
2020-05-15 05:33:08 +08:00
// if `allowParens` is not set to true don't bother wrapping in parens
2020-03-31 20:40:00 +08:00
return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
2020-03-07 11:45:40 +08:00
}
});
}
}
return {
ArrowFunctionExpression: checkArrowFunc
};
}
};