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",
33 url
: "https://eslint.org/docs/rules/no-unneeded-ternary"
45 additionalProperties
: false
52 unnecessaryConditionalExpression
: "Unnecessary use of boolean literals in conditional expression.",
53 unnecessaryConditionalAssignment
: "Unnecessary use of conditional expression for default assignment."
58 const options
= context
.options
[0] || {};
59 const defaultAssignment
= options
.defaultAssignment
!== false;
60 const sourceCode
= context
.getSourceCode();
63 * Test if the node is a boolean literal
64 * @param {ASTNode} node The node to report.
65 * @returns {boolean} True if the its a boolean literal
68 function isBooleanLiteral(node
) {
69 return node
.type
=== "Literal" && typeof node
.value
=== "boolean";
73 * Creates an expression that represents the boolean inverse of the expression represented by the original node
74 * @param {ASTNode} node A node representing an expression
75 * @returns {string} A string representing an inverted expression
77 function invertExpression(node
) {
78 if (node
.type
=== "BinaryExpression" && Object
.prototype.hasOwnProperty
.call(OPERATOR_INVERSES
, node
.operator
)) {
79 const operatorToken
= sourceCode
.getFirstTokenBetween(
82 token
=> token
.value
=== node
.operator
84 const text
= sourceCode
.getText();
86 return text
.slice(node
.range
[0],
87 operatorToken
.range
[0]) + OPERATOR_INVERSES
[node
.operator
] + text
.slice(operatorToken
.range
[1], node
.range
[1]);
90 if (astUtils
.getPrecedence(node
) < astUtils
.getPrecedence({ type
: "UnaryExpression" })) {
91 return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
93 return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
97 * Tests if a given node always evaluates to a boolean value
98 * @param {ASTNode} node An expression node
99 * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
101 function isBooleanExpression(node
) {
102 return node
.type
=== "BinaryExpression" && BOOLEAN_OPERATORS
.has(node
.operator
) ||
103 node
.type
=== "UnaryExpression" && node
.operator
=== "!";
107 * Test if the node matches the pattern id ? id : expression
108 * @param {ASTNode} node The ConditionalExpression to check.
109 * @returns {boolean} True if the pattern is matched, and false otherwise
112 function matchesDefaultAssignment(node
) {
113 return node
.test
.type
=== "Identifier" &&
114 node
.consequent
.type
=== "Identifier" &&
115 node
.test
.name
=== node
.consequent
.name
;
120 ConditionalExpression(node
) {
121 if (isBooleanLiteral(node
.alternate
) && isBooleanLiteral(node
.consequent
)) {
124 messageId
: "unnecessaryConditionalExpression",
126 if (node
.consequent
.value
=== node
.alternate
.value
) {
128 // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
129 return node
.test
.type
=== "Identifier" ? fixer
.replaceText(node
, node
.consequent
.value
.toString()) : null;
131 if (node
.alternate
.value
) {
133 // Replace `foo() ? false : true` with `!(foo())`
134 return fixer
.replaceText(node
, invertExpression(node
.test
));
137 // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
139 return fixer
.replaceText(node
, isBooleanExpression(node
.test
) ? astUtils
.getParenthesisedText(sourceCode
, node
.test
) : `!${invertExpression(node.test)}`);
142 } else if (!defaultAssignment
&& matchesDefaultAssignment(node
)) {
145 messageId
: "unnecessaryConditionalAssignment",
147 const shouldParenthesizeAlternate
=
149 astUtils
.getPrecedence(node
.alternate
) < OR_PRECEDENCE
||
150 astUtils
.isCoalesceExpression(node
.alternate
)
152 !astUtils
.isParenthesised(sourceCode
, node
.alternate
);
153 const alternateText
= shouldParenthesizeAlternate
154 ? `(${sourceCode.getText(node.alternate)})`
155 : astUtils
.getParenthesisedText(sourceCode
, node
.alternate
);
156 const testText
= astUtils
.getParenthesisedText(sourceCode
, node
.test
);
158 return fixer
.replaceText(node
, `${testText} || ${alternateText}`);