parentheses.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const {isParenthesized, isOpeningParenToken, isClosingParenToken} = require('@eslint-community/eslint-utils');
  3. /*
  4. Get how many times the node is parenthesized.
  5. @param {Node} node - The node to be checked.
  6. @param {SourceCode} sourceCode - The source code object.
  7. @returns {number}
  8. */
  9. function getParenthesizedTimes(node, sourceCode) {
  10. let times = 0;
  11. while (isParenthesized(times + 1, node, sourceCode)) {
  12. times++;
  13. }
  14. return times;
  15. }
  16. /*
  17. Get all parentheses tokens around the node.
  18. @param {Node} node - The node to be checked.
  19. @param {SourceCode} sourceCode - The source code object.
  20. @returns {Token[]}
  21. */
  22. function getParentheses(node, sourceCode) {
  23. const count = getParenthesizedTimes(node, sourceCode);
  24. if (count === 0) {
  25. return [];
  26. }
  27. return [
  28. ...sourceCode.getTokensBefore(node, {count, filter: isOpeningParenToken}),
  29. ...sourceCode.getTokensAfter(node, {count, filter: isClosingParenToken}),
  30. ];
  31. }
  32. /*
  33. Get the parenthesized range of the node.
  34. @param {Node} node - The node to be checked.
  35. @param {SourceCode} sourceCode - The source code object.
  36. @returns {number[]}
  37. */
  38. function getParenthesizedRange(node, sourceCode) {
  39. const parentheses = getParentheses(node, sourceCode);
  40. const [start] = (parentheses[0] || node).range;
  41. const [, end] = (parentheses[parentheses.length - 1] || node).range;
  42. return [start, end];
  43. }
  44. /*
  45. Get the parenthesized text of the node.
  46. @param {Node} node - The node to be checked.
  47. @param {SourceCode} sourceCode - The source code object.
  48. @returns {string}
  49. */
  50. function getParenthesizedText(node, sourceCode) {
  51. const [start, end] = getParenthesizedRange(node, sourceCode);
  52. return sourceCode.text.slice(start, end);
  53. }
  54. module.exports = {
  55. isParenthesized,
  56. getParenthesizedTimes,
  57. getParentheses,
  58. getParenthesizedRange,
  59. getParenthesizedText,
  60. };