index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. import KEYS from "./visitor-keys.js";
  6. /**
  7. * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
  8. */
  9. // List to ignore keys.
  10. const KEY_BLACKLIST = new Set([
  11. "parent",
  12. "leadingComments",
  13. "trailingComments"
  14. ]);
  15. /**
  16. * Check whether a given key should be used or not.
  17. * @param {string} key The key to check.
  18. * @returns {boolean} `true` if the key should be used.
  19. */
  20. function filterKey(key) {
  21. return !KEY_BLACKLIST.has(key) && key[0] !== "_";
  22. }
  23. /* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
  24. TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
  25. */
  26. /**
  27. * Get visitor keys of a given node.
  28. * @param {Object} node The AST node to get keys.
  29. * @returns {readonly string[]} Visitor keys of the node.
  30. */
  31. export function getKeys(node) {
  32. return Object.keys(node).filter(filterKey);
  33. }
  34. /* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */
  35. /**
  36. * Make the union set with `KEYS` and given keys.
  37. * @param {VisitorKeys} additionalKeys The additional keys.
  38. * @returns {VisitorKeys} The union set.
  39. */
  40. export function unionWith(additionalKeys) {
  41. const retv = /** @type {{ [type: string]: ReadonlyArray<string> }} */
  42. (Object.assign({}, KEYS));
  43. for (const type of Object.keys(additionalKeys)) {
  44. if (Object.hasOwn(retv, type)) {
  45. const keys = new Set(additionalKeys[type]);
  46. for (const key of retv[type]) {
  47. keys.add(key);
  48. }
  49. retv[type] = Object.freeze(Array.from(keys));
  50. } else {
  51. retv[type] = Object.freeze(Array.from(additionalKeys[type]));
  52. }
  53. }
  54. return Object.freeze(retv);
  55. }
  56. export { KEYS };