Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

no-unneeded-ternary.js 6.4KB

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