prefer-logical-operator-over-ternary.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. 'use strict';
  2. const {isParenthesized, getParenthesizedText} = require('./utils/parentheses.js');
  3. const isSameReference = require('./utils/is-same-reference.js');
  4. const shouldAddParenthesesToLogicalExpressionChild = require('./utils/should-add-parentheses-to-logical-expression-child.js');
  5. const needsSemicolon = require('./utils/needs-semicolon.js');
  6. const MESSAGE_ID_ERROR = 'prefer-logical-operator-over-ternary/error';
  7. const MESSAGE_ID_SUGGESTION = 'prefer-logical-operator-over-ternary/suggestion';
  8. const messages = {
  9. [MESSAGE_ID_ERROR]: 'Prefer using a logical operator over a ternary.',
  10. [MESSAGE_ID_SUGGESTION]: 'Switch to `{{operator}}` operator.',
  11. };
  12. function isSameNode(left, right, sourceCode) {
  13. if (isSameReference(left, right)) {
  14. return true;
  15. }
  16. if (left.type !== right.type) {
  17. return false;
  18. }
  19. switch (left.type) {
  20. case 'AwaitExpression': {
  21. return isSameNode(left.argument, right.argument, sourceCode);
  22. }
  23. case 'LogicalExpression': {
  24. return (
  25. left.operator === right.operator
  26. && isSameNode(left.left, right.left, sourceCode)
  27. && isSameNode(left.right, right.right, sourceCode)
  28. );
  29. }
  30. case 'UnaryExpression': {
  31. return (
  32. left.operator === right.operator
  33. && left.prefix === right.prefix
  34. && isSameNode(left.argument, right.argument, sourceCode)
  35. );
  36. }
  37. case 'UpdateExpression': {
  38. return false;
  39. }
  40. // No default
  41. }
  42. return sourceCode.getText(left) === sourceCode.getText(right);
  43. }
  44. function fix({
  45. fixer,
  46. sourceCode,
  47. conditionalExpression,
  48. left,
  49. right,
  50. operator,
  51. }) {
  52. let text = [left, right].map((node, index) => {
  53. const isNodeParenthesized = isParenthesized(node, sourceCode);
  54. let text = isNodeParenthesized ? getParenthesizedText(node, sourceCode) : sourceCode.getText(node);
  55. if (
  56. !isNodeParenthesized
  57. && shouldAddParenthesesToLogicalExpressionChild(node, {operator, property: index === 0 ? 'left' : 'right'})
  58. ) {
  59. text = `(${text})`;
  60. }
  61. return text;
  62. }).join(` ${operator} `);
  63. // According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table
  64. // There should be no cases need add parentheses when switching ternary to logical expression
  65. // ASI
  66. if (needsSemicolon(sourceCode.getTokenBefore(conditionalExpression), sourceCode, text)) {
  67. text = `;${text}`;
  68. }
  69. return fixer.replaceText(conditionalExpression, text);
  70. }
  71. function getProblem({
  72. sourceCode,
  73. conditionalExpression,
  74. left,
  75. right,
  76. }) {
  77. return {
  78. node: conditionalExpression,
  79. messageId: MESSAGE_ID_ERROR,
  80. suggest: ['??', '||'].map(operator => ({
  81. messageId: MESSAGE_ID_SUGGESTION,
  82. data: {operator},
  83. fix: fixer => fix({
  84. fixer,
  85. sourceCode,
  86. conditionalExpression,
  87. left,
  88. right,
  89. operator,
  90. }),
  91. })),
  92. };
  93. }
  94. /** @param {import('eslint').Rule.RuleContext} context */
  95. const create = context => {
  96. const sourceCode = context.getSourceCode();
  97. return {
  98. ConditionalExpression(conditionalExpression) {
  99. const {test, consequent, alternate} = conditionalExpression;
  100. // `foo ? foo : bar`
  101. if (isSameNode(test, consequent, sourceCode)) {
  102. return getProblem({
  103. sourceCode,
  104. conditionalExpression,
  105. left: test,
  106. right: alternate,
  107. });
  108. }
  109. // `!bar ? foo : bar`
  110. if (
  111. test.type === 'UnaryExpression'
  112. && test.operator === '!'
  113. && test.prefix
  114. && isSameNode(test.argument, alternate, sourceCode)
  115. ) {
  116. return getProblem({
  117. sourceCode,
  118. conditionalExpression,
  119. left: test.argument,
  120. right: consequent,
  121. });
  122. }
  123. },
  124. };
  125. };
  126. /** @type {import('eslint').Rule.RuleModule} */
  127. module.exports = {
  128. create,
  129. meta: {
  130. type: 'suggestion',
  131. docs: {
  132. description: 'Prefer using a logical operator over a ternary.',
  133. },
  134. hasSuggestions: true,
  135. messages,
  136. },
  137. };