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