UNPKG

6.35 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 },
32
33 schema: [
34 {
35 type: "object",
36 properties: {
37 defaultAssignment: {
38 type: "boolean"
39 }
40 },
41 additionalProperties: false
42 }
43 ],
44
45 fixable: "code"
46 },
47
48 create(context) {
49 const options = context.options[0] || {};
50 const defaultAssignment = options.defaultAssignment !== false;
51 const sourceCode = context.getSourceCode();
52
53 /**
54 * Test if the node is a boolean literal
55 * @param {ASTNode} node - The node to report.
56 * @returns {boolean} True if the its a boolean literal
57 * @private
58 */
59 function isBooleanLiteral(node) {
60 return node.type === "Literal" && typeof node.value === "boolean";
61 }
62
63 /**
64 * Creates an expression that represents the boolean inverse of the expression represented by the original node
65 * @param {ASTNode} node A node representing an expression
66 * @returns {string} A string representing an inverted expression
67 */
68 function invertExpression(node) {
69 if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) {
70 const operatorToken = sourceCode.getFirstTokenBetween(
71 node.left,
72 node.right,
73 token => token.value === node.operator
74 );
75
76 return sourceCode.getText().slice(node.range[0], operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + sourceCode.getText().slice(operatorToken.range[1], node.range[1]);
77 }
78
79 if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) {
80 return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
81 }
82 return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
83 }
84
85 /**
86 * Tests if a given node always evaluates to a boolean value
87 * @param {ASTNode} node - An expression node
88 * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
89 */
90 function isBooleanExpression(node) {
91 return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) ||
92 node.type === "UnaryExpression" && node.operator === "!";
93 }
94
95 /**
96 * Test if the node matches the pattern id ? id : expression
97 * @param {ASTNode} node - The ConditionalExpression to check.
98 * @returns {boolean} True if the pattern is matched, and false otherwise
99 * @private
100 */
101 function matchesDefaultAssignment(node) {
102 return node.test.type === "Identifier" &&
103 node.consequent.type === "Identifier" &&
104 node.test.name === node.consequent.name;
105 }
106
107 return {
108
109 ConditionalExpression(node) {
110 if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) {
111 context.report({
112 node,
113 loc: node.consequent.loc.start,
114 message: "Unnecessary use of boolean literals in conditional expression.",
115 fix(fixer) {
116 if (node.consequent.value === node.alternate.value) {
117
118 // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
119 return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null;
120 }
121 if (node.alternate.value) {
122
123 // Replace `foo() ? false : true` with `!(foo())`
124 return fixer.replaceText(node, invertExpression(node.test));
125 }
126
127 // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
128
129 return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`);
130 }
131 });
132 } else if (!defaultAssignment && matchesDefaultAssignment(node)) {
133 context.report({
134 node,
135 loc: node.consequent.loc.start,
136 message: "Unnecessary use of conditional expression for default assignment.",
137 fix: fixer => {
138 let nodeAlternate = astUtils.getParenthesisedText(sourceCode, node.alternate);
139
140 if (node.alternate.type === "ConditionalExpression") {
141 const isAlternateParenthesised = astUtils.isParenthesised(sourceCode, node.alternate);
142
143 nodeAlternate = isAlternateParenthesised ? nodeAlternate : `(${nodeAlternate})`;
144 }
145
146 return fixer.replaceText(node, `${astUtils.getParenthesisedText(sourceCode, node.test)} || ${nodeAlternate}`);
147 }
148 });
149 }
150 }
151 };
152 }
153};