2 * @fileoverview Rule to flag no-unneeded-ternary
3 * @author Gyandeep Singh
8 const astUtils = require("./utils/ast-utils");
10 // Operators that always result in a boolean value
11 const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]);
12 const OPERATOR_INVERSES = {
18 // Operators like < and >= are not true inverses, since both will return false with NaN.
20 const OR_PRECEDENCE = astUtils.getPrecedence({ type: "LogicalExpression", operator: "||" });
22 //------------------------------------------------------------------------------
24 //------------------------------------------------------------------------------
31 description: "disallow ternary operators when simpler alternatives exist",
32 category: "Stylistic Issues",
34 url: "https://eslint.org/docs/rules/no-unneeded-ternary"
46 additionalProperties: false
54 const options = context.options[0] || {};
55 const defaultAssignment = options.defaultAssignment !== false;
56 const sourceCode = context.getSourceCode();
59 * Test if the node is a boolean literal
60 * @param {ASTNode} node The node to report.
61 * @returns {boolean} True if the its a boolean literal
64 function isBooleanLiteral(node) {
65 return node.type === "Literal" && typeof node.value === "boolean";
69 * Creates an expression that represents the boolean inverse of the expression represented by the original node
70 * @param {ASTNode} node A node representing an expression
71 * @returns {string} A string representing an inverted expression
73 function invertExpression(node) {
74 if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) {
75 const operatorToken = sourceCode.getFirstTokenBetween(
78 token => token.value === node.operator
80 const text = sourceCode.getText();
82 return text.slice(node.range[0],
83 operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]);
86 if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) {
87 return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
89 return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
93 * Tests if a given node always evaluates to a boolean value
94 * @param {ASTNode} node An expression node
95 * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
97 function isBooleanExpression(node) {
98 return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) ||
99 node.type === "UnaryExpression" && node.operator === "!";
103 * Test if the node matches the pattern id ? id : expression
104 * @param {ASTNode} node The ConditionalExpression to check.
105 * @returns {boolean} True if the pattern is matched, and false otherwise
108 function matchesDefaultAssignment(node) {
109 return node.test.type === "Identifier" &&
110 node.consequent.type === "Identifier" &&
111 node.test.name === node.consequent.name;
116 ConditionalExpression(node) {
117 if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) {
120 loc: node.consequent.loc.start,
121 message: "Unnecessary use of boolean literals in conditional expression.",
123 if (node.consequent.value === node.alternate.value) {
125 // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
126 return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null;
128 if (node.alternate.value) {
130 // Replace `foo() ? false : true` with `!(foo())`
131 return fixer.replaceText(node, invertExpression(node.test));
134 // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
136 return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`);
139 } else if (!defaultAssignment && matchesDefaultAssignment(node)) {
142 loc: node.consequent.loc.start,
143 message: "Unnecessary use of conditional expression for default assignment.",
145 const shouldParenthesizeAlternate = (
146 astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE &&
147 !astUtils.isParenthesised(sourceCode, node.alternate)
149 const alternateText = shouldParenthesizeAlternate
150 ? `(${sourceCode.getText(node.alternate)})`
151 : astUtils.getParenthesisedText(sourceCode, node.alternate);
152 const testText = astUtils.getParenthesisedText(sourceCode, node.test);
154 return fixer.replaceText(node, `${testText} || ${alternateText}`);