UNPKG

6.46 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag no-unneeded-ternary
3 * @author Gyandeep Singh
4 */
5
6"use strict";
7
8const astUtils = require("../ast-utils");
9
10// Operators that always result in a boolean value
11const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]);
12const OPERATOR_INVERSES = {
13 "==": "!=",
14 "!=": "==",
15 "===": "!==",
16 "!==": "==="
17
18 // Operators like < and >= are not true inverses, since both will return false with NaN.
19};
20
21//------------------------------------------------------------------------------
22// Rule Definition
23//------------------------------------------------------------------------------
24
25module.exports = {
26 meta: {
27 docs: {
28 description: "disallow ternary operators when simpler alternatives exist",
29 category: "Stylistic Issues",
30 recommended: false,
31 url: "https://eslint.org/docs/rules/no-unneeded-ternary"
32 },
33
34 schema: [
35 {
36 type: "object",
37 properties: {
38 defaultAssignment: {
39 type: "boolean"
40 }
41 },
42 additionalProperties: false
43 }
44 ],
45
46 fixable: "code"
47 },
48
49 create(context) {
50 const options = context.options[0] || {};
51 const defaultAssignment = options.defaultAssignment !== false;
52 const sourceCode = context.getSourceCode();
53
54 /**
55 * Test if the node is a boolean literal
56 * @param {ASTNode} node - The node to report.
57 * @returns {boolean} True if the its a boolean literal
58 * @private
59 */
60 function isBooleanLiteral(node) {
61 return node.type === "Literal" && typeof node.value === "boolean";
62 }
63
64 /**
65 * Creates an expression that represents the boolean inverse of the expression represented by the original node
66 * @param {ASTNode} node A node representing an expression
67 * @returns {string} A string representing an inverted expression
68 */
69 function invertExpression(node) {
70 if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) {
71 const operatorToken = sourceCode.getFirstTokenBetween(
72 node.left,
73 node.right,
74 token => token.value === node.operator
75 );
76 const text = sourceCode.getText();
77
78 return text.slice(node.range[0],
79 operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]);
80 }
81
82 if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) {
83 return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
84 }
85 return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
86 }
87
88 /**
89 * Tests if a given node always evaluates to a boolean value
90 * @param {ASTNode} node - An expression node
91 * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
92 */
93 function isBooleanExpression(node) {
94 return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) ||
95 node.type === "UnaryExpression" && node.operator === "!";
96 }
97
98 /**
99 * Test if the node matches the pattern id ? id : expression
100 * @param {ASTNode} node - The ConditionalExpression to check.
101 * @returns {boolean} True if the pattern is matched, and false otherwise
102 * @private
103 */
104 function matchesDefaultAssignment(node) {
105 return node.test.type === "Identifier" &&
106 node.consequent.type === "Identifier" &&
107 node.test.name === node.consequent.name;
108 }
109
110 return {
111
112 ConditionalExpression(node) {
113 if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) {
114 context.report({
115 node,
116 loc: node.consequent.loc.start,
117 message: "Unnecessary use of boolean literals in conditional expression.",
118 fix(fixer) {
119 if (node.consequent.value === node.alternate.value) {
120
121 // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
122 return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null;
123 }
124 if (node.alternate.value) {
125
126 // Replace `foo() ? false : true` with `!(foo())`
127 return fixer.replaceText(node, invertExpression(node.test));
128 }
129
130 // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
131
132 return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`);
133 }
134 });
135 } else if (!defaultAssignment && matchesDefaultAssignment(node)) {
136 context.report({
137 node,
138 loc: node.consequent.loc.start,
139 message: "Unnecessary use of conditional expression for default assignment.",
140 fix: fixer => {
141 let nodeAlternate = astUtils.getParenthesisedText(sourceCode, node.alternate);
142
143 if (node.alternate.type === "ConditionalExpression") {
144 const isAlternateParenthesised = astUtils.isParenthesised(sourceCode, node.alternate);
145
146 nodeAlternate = isAlternateParenthesised ? nodeAlternate : `(${nodeAlternate})`;
147 }
148
149 return fixer.replaceText(node, `${astUtils.getParenthesisedText(sourceCode, node.test)} || ${nodeAlternate}`);
150 }
151 });
152 }
153 }
154 };
155 }
156};