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

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