no-unneeded-ternary.js 6.6 KB

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