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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. // We are not using this, but we can improve this function with it
  10. /* c8 ignore next 3 */
  11. if (!property) {
  12. throw new Error('`property` is required.');
  13. }
  14. if (
  15. node.type === 'LogicalExpression'
  16. && node.operator === operator
  17. ) {
  18. return false;
  19. }
  20. // Not really needed, but more readable
  21. if (
  22. node.type === 'AwaitExpression'
  23. || node.type === 'BinaryExpression'
  24. ) {
  25. return true;
  26. }
  27. // Lower precedence than `LogicalExpression`
  28. // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
  29. if (
  30. node.type === 'LogicalExpression'
  31. || node.type === 'ConditionalExpression'
  32. || node.type === 'AssignmentExpression'
  33. || node.type === 'ArrowFunctionExpression'
  34. || node.type === 'YieldExpression'
  35. || node.type === 'SequenceExpression'
  36. ) {
  37. return true;
  38. }
  39. return false;
  40. }
  41. module.exports = shouldAddParenthesesToLogicalExpressionChild;