source-code-visitor.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @fileoverview SourceCodeVisitor class
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //-----------------------------------------------------------------------------
  7. // Helpers
  8. //-----------------------------------------------------------------------------
  9. const emptyArray = Object.freeze([]);
  10. //------------------------------------------------------------------------------
  11. // Exports
  12. //------------------------------------------------------------------------------
  13. /**
  14. * A structure to hold a list of functions to call for a given name.
  15. * This is used to allow multiple rules to register functions for a given name
  16. * without having to know about each other.
  17. */
  18. class SourceCodeVisitor {
  19. /**
  20. * The functions to call for a given name.
  21. * @type {Map<string, Function[]>}
  22. */
  23. #functions = new Map();
  24. /**
  25. * Adds a function to the list of functions to call for a given name.
  26. * @param {string} name The name of the function to call.
  27. * @param {Function} func The function to call.
  28. * @returns {void}
  29. */
  30. add(name, func) {
  31. if (this.#functions.has(name)) {
  32. this.#functions.get(name).push(func);
  33. } else {
  34. this.#functions.set(name, [func]);
  35. }
  36. }
  37. /**
  38. * Gets the list of functions to call for a given name.
  39. * @param {string} name The name of the function to call.
  40. * @returns {Function[]} The list of functions to call.
  41. */
  42. get(name) {
  43. if (this.#functions.has(name)) {
  44. return this.#functions.get(name);
  45. }
  46. return emptyArray;
  47. }
  48. /**
  49. * Iterates over all names and calls the callback with the name.
  50. * @param {(name:string) => void} callback The callback to call for each name.
  51. * @returns {void}
  52. */
  53. forEachName(callback) {
  54. this.#functions.forEach((funcs, name) => {
  55. callback(name);
  56. });
  57. }
  58. /**
  59. * Calls the functions for a given name with the given arguments.
  60. * @param {string} name The name of the function to call.
  61. * @param {any[]} args The arguments to pass to the function.
  62. * @returns {void}
  63. */
  64. callSync(name, ...args) {
  65. if (this.#functions.has(name)) {
  66. this.#functions.get(name).forEach(func => func(...args));
  67. }
  68. }
  69. }
  70. module.exports = { SourceCodeVisitor };