HookMap.js 1.5 KB

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