parentheses.js 1.9 KB

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