should-add-parentheses-to-logical-expression-child.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. /**
  3. Check if parentheses should be added to a `node` when it's used as child of `LogicalExpression`.
  4. @param {Node} node - The AST node to check.
  5. @param {{operator: string, property: string}} options - Options
  6. @returns {boolean}
  7. */
  8. function shouldAddParenthesesToLogicalExpressionChild(node, {operator, property}) {
  9. /* istanbul ignore next: When operator or property is different, need check `LogicalExpression` operator precedence, not implemented */
  10. if (operator !== '??' || property !== 'left') {
  11. throw new Error('Not supported.');
  12. }
  13. // Not really needed, but more readable
  14. if (
  15. node.type === 'AwaitExpression'
  16. || node.type === 'BinaryExpression'
  17. ) {
  18. return true;
  19. }
  20. // Lower precedence than `LogicalExpression`
  21. // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
  22. if (
  23. node.type === 'ConditionalExpression'
  24. || node.type === 'AssignmentExpression'
  25. || node.type === 'AssignmentExpression'
  26. || node.type === 'YieldExpression'
  27. || node.type === 'SequenceExpression'
  28. ) {
  29. return true;
  30. }
  31. return false;
  32. }
  33. module.exports = shouldAddParenthesesToLogicalExpressionChild;