HookMap.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. class HookMap {
  7. constructor(factory) {
  8. this._map = new Map();
  9. this._factory = factory;
  10. this._interceptors = [];
  11. }
  12. get(key) {
  13. return this._map.get(key);
  14. }
  15. for(key) {
  16. const hook = this.get(key);
  17. if(hook !== undefined) {
  18. return hook;
  19. }
  20. let newHook = this._factory(key);
  21. const interceptors = this._interceptors;
  22. for(let i = 0; i < interceptors.length; i++) {
  23. newHook = interceptors[i].factory(key, newHook);
  24. }
  25. this._map.set(key, newHook);
  26. return newHook;
  27. }
  28. intercept(interceptor) {
  29. this._interceptors.push(Object.assign({
  30. factory: (key, hook) => hook
  31. }, interceptor));
  32. }
  33. tap(key, options, fn) {
  34. return this.for(key).tap(options, fn);
  35. }
  36. tapAsync(key, options, fn) {
  37. return this.for(key).tapAsync(options, fn);
  38. }
  39. tapPromise(key, options, fn) {
  40. return this.for(key).tapPromise(options, fn);
  41. }
  42. }
  43. module.exports = HookMap;