]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-unneeded-ternary.js
change from CLIEngine to ESLint
[pve-eslint.git] / eslint / lib / rules / no-unneeded-ternary.js
1 /**
2 * @fileoverview Rule to flag no-unneeded-ternary
3 * @author Gyandeep Singh
4 */
5
6 "use strict";
7
8 const astUtils = require("./utils/ast-utils");
9
10 // Operators that always result in a boolean value
11 const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]);
12 const OPERATOR_INVERSES = {
13 "==": "!=",
14 "!=": "==",
15 "===": "!==",
16 "!==": "==="
17
18 // Operators like < and >= are not true inverses, since both will return false with NaN.
19 };
20 const OR_PRECEDENCE = astUtils.getPrecedence({ type: "LogicalExpression", operator: "||" });
21
22 //------------------------------------------------------------------------------
23 // Rule Definition
24 //------------------------------------------------------------------------------
25
26 module.exports = {
27 meta: {
28 type: "suggestion",
29
30 docs: {
31 description: "disallow ternary operators when simpler alternatives exist",
32 recommended: false,
33 url: "https://eslint.org/docs/rules/no-unneeded-ternary"
34 },
35
36 schema: [
37 {
38 type: "object",
39 properties: {
40 defaultAssignment: {
41 type: "boolean",
42 default: true
43 }
44 },
45 additionalProperties: false
46 }
47 ],
48
49 fixable: "code",
50
51 messages: {
52 unnecessaryConditionalExpression: "Unnecessary use of boolean literals in conditional expression.",
53 unnecessaryConditionalAssignment: "Unnecessary use of conditional expression for default assignment."
54 }
55 },
56
57 create(context) {
58 const options = context.options[0] || {};
59 const defaultAssignment = options.defaultAssignment !== false;
60 const sourceCode = context.getSourceCode();
61
62 /**
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
66 * @private
67 */
68 function isBooleanLiteral(node) {
69 return node.type === "Literal" && typeof node.value === "boolean";
70 }
71
72 /**
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
76 */
77 function invertExpression(node) {
78 if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) {
79 const operatorToken = sourceCode.getFirstTokenBetween(
80 node.left,
81 node.right,
82 token => token.value === node.operator
83 );
84 const text = sourceCode.getText();
85
86 return text.slice(node.range[0],
87 operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]);
88 }
89
90 if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) {
91 return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
92 }
93 return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
94 }
95
96 /**
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
100 */
101 function isBooleanExpression(node) {
102 return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) ||
103 node.type === "UnaryExpression" && node.operator === "!";
104 }
105
106 /**
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
110 * @private
111 */
112 function matchesDefaultAssignment(node) {
113 return node.test.type === "Identifier" &&
114 node.consequent.type === "Identifier" &&
115 node.test.name === node.consequent.name;
116 }
117
118 return {
119
120 ConditionalExpression(node) {
121 if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) {
122 context.report({
123 node,
124 messageId: "unnecessaryConditionalExpression",
125 fix(fixer) {
126 if (node.consequent.value === node.alternate.value) {
127
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;
130 }
131 if (node.alternate.value) {
132
133 // Replace `foo() ? false : true` with `!(foo())`
134 return fixer.replaceText(node, invertExpression(node.test));
135 }
136
137 // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
138
139 return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`);
140 }
141 });
142 } else if (!defaultAssignment && matchesDefaultAssignment(node)) {
143 context.report({
144 node,
145 messageId: "unnecessaryConditionalAssignment",
146 fix: fixer => {
147 const shouldParenthesizeAlternate =
148 (
149 astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE ||
150 astUtils.isCoalesceExpression(node.alternate)
151 ) &&
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);
157
158 return fixer.replaceText(node, `${testText} || ${alternateText}`);
159 }
160 });
161 }
162 }
163 };
164 }
165 };