Actualizacion maquina principal
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / 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             category: "Stylistic Issues",
33             recommended: false,
34             url: "https://eslint.org/docs/rules/no-unneeded-ternary"
35         },
36
37         schema: [
38             {
39                 type: "object",
40                 properties: {
41                     defaultAssignment: {
42                         type: "boolean",
43                         default: true
44                     }
45                 },
46                 additionalProperties: false
47             }
48         ],
49
50         fixable: "code"
51     },
52
53     create(context) {
54         const options = context.options[0] || {};
55         const defaultAssignment = options.defaultAssignment !== false;
56         const sourceCode = context.getSourceCode();
57
58         /**
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
62          * @private
63          */
64         function isBooleanLiteral(node) {
65             return node.type === "Literal" && typeof node.value === "boolean";
66         }
67
68         /**
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
72          */
73         function invertExpression(node) {
74             if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) {
75                 const operatorToken = sourceCode.getFirstTokenBetween(
76                     node.left,
77                     node.right,
78                     token => token.value === node.operator
79                 );
80                 const text = sourceCode.getText();
81
82                 return text.slice(node.range[0],
83                     operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]);
84             }
85
86             if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) {
87                 return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
88             }
89             return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
90         }
91
92         /**
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
96          */
97         function isBooleanExpression(node) {
98             return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) ||
99                 node.type === "UnaryExpression" && node.operator === "!";
100         }
101
102         /**
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
106          * @private
107          */
108         function matchesDefaultAssignment(node) {
109             return node.test.type === "Identifier" &&
110                    node.consequent.type === "Identifier" &&
111                    node.test.name === node.consequent.name;
112         }
113
114         return {
115
116             ConditionalExpression(node) {
117                 if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) {
118                     context.report({
119                         node,
120                         loc: node.consequent.loc.start,
121                         message: "Unnecessary use of boolean literals in conditional expression.",
122                         fix(fixer) {
123                             if (node.consequent.value === node.alternate.value) {
124
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;
127                             }
128                             if (node.alternate.value) {
129
130                                 // Replace `foo() ? false : true` with `!(foo())`
131                                 return fixer.replaceText(node, invertExpression(node.test));
132                             }
133
134                             // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
135
136                             return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`);
137                         }
138                     });
139                 } else if (!defaultAssignment && matchesDefaultAssignment(node)) {
140                     context.report({
141                         node,
142                         loc: node.consequent.loc.start,
143                         message: "Unnecessary use of conditional expression for default assignment.",
144                         fix: fixer => {
145                             const shouldParenthesizeAlternate = (
146                                 astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE &&
147                                 !astUtils.isParenthesised(sourceCode, node.alternate)
148                             );
149                             const alternateText = shouldParenthesizeAlternate
150                                 ? `(${sourceCode.getText(node.alternate)})`
151                                 : astUtils.getParenthesisedText(sourceCode, node.alternate);
152                             const testText = astUtils.getParenthesisedText(sourceCode, node.test);
153
154                             return fixer.replaceText(node, `${testText} || ${alternateText}`);
155                         }
156                     });
157                 }
158             }
159         };
160     }
161 };