no-unneeded-ternary.js 6.4 KB

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