merge-visitors-in-place.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. /**
  7. * Merge two visitors.
  8. * This function modifies `visitor1` directly to merge.
  9. * @param {Visitor} visitor1 The visitor which is assigned.
  10. * @param {Visitor} visitor2 The visitor which is assigning.
  11. * @returns {Visitor} `visitor1`.
  12. */
  13. module.exports = function mergeVisitorsInPlace(visitor1, visitor2) {
  14. for (const key of Object.keys(visitor2)) {
  15. const handler1 = visitor1[key]
  16. const handler2 = visitor2[key]
  17. if (typeof handler1 === "function") {
  18. if (handler1._handlers) {
  19. handler1._handlers.push(handler2)
  20. } else {
  21. const handlers = [handler1, handler2]
  22. visitor1[key] = Object.assign(dispatch.bind(null, handlers), {
  23. _handlers: handlers,
  24. })
  25. }
  26. } else {
  27. visitor1[key] = handler2
  28. }
  29. }
  30. return visitor1
  31. }
  32. /**
  33. * Dispatch all given functions with a node.
  34. * @param {function[]} handlers The function list to call.
  35. * @param {Node} node The AST node to be handled.
  36. * @returns {void}
  37. */
  38. function dispatch(handlers, node) {
  39. for (const h of handlers) {
  40. h(node)
  41. }
  42. }