no-unneeded-ternary.js 6.3 KB

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