HookMap.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 tap(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 tapAsync(
  46. key,
  47. options,
  48. fn
  49. ) {
  50. return this.for(key).tapAsync(options, fn);
  51. }, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead.");
  52. HookMap.prototype.tapPromise = util.deprecate(function tapPromise(
  53. key,
  54. options,
  55. fn
  56. ) {
  57. return this.for(key).tapPromise(options, fn);
  58. }, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead.");
  59. module.exports = HookMap;