-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.object.js
75 lines (63 loc) · 2.4 KB
/
index.object.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
let errorMessages = {
1: `.latch() expects at least two arguments, a hook name and a callback.`,
2: '.latch() expects a string for the hook name.',
3: '.latch() expects a function for the latch callback.',
10: '.unlatch() expects exactly two arguments, the latch id and the hook name.',
11: '.unlatch() expects a Symbol for the latch id.',
12: '.unlatch() expects a string for the hook name.',
20: '.hook() expects at least two arguments, the hook name and the initial result.',
21: '.hook() expects a string for the hook name.'
}
let hooksMixin = {
_hooks: {},
at: function () {
return this.latch.apply(this, arguments)
},
latch: function (hookName, latchCallback, ...latchParams) {
// check
if (arguments.length < 2)
throw new Error(errorMessages[1])
if (typeof arguments[0] !== 'string')
throw new TypeError(errorMessages[2])
if (typeof arguments[1] !== 'function')
throw new TypeError(errorMessages[3])
// register hook
if (hookName in this._hooks === false)
this._hooks[hookName] = []
// add latch
let latchId = Symbol(`Latch for the hook '${hookName}'`)
this._hooks[hookName].push({
id: latchId,
fn: latchCallback,
pr: latchParams
})
return latchId
},
unlatch: function (latchId, hookName) {
// check
if (arguments.length !== 2)
throw new Error(errorMessages[10])
if (typeof arguments[0] !== 'symbol')
throw new TypeError(errorMessages[11])
if (typeof arguments[1] !== 'string')
throw new TypeError(errorMessages[12])
// remove latch
if (hookName in this._hooks)
this._hooks[hookName] = this._hooks[hookName].filter(latch => latch.id !== latchId)
},
hook: function (hookName, result, ...hookParams) {
// check
if (arguments.length < 2)
throw new Error(errorMessages[20])
if (typeof arguments[0] !== 'string')
throw new TypeError(errorMessages[21])
// pick up latches
if (hookName in this._hooks) {
this._hooks[hookName].forEach(latch => {
result = latch.fn.apply(this, hookParams.concat(result, latch.pr))
})
}
return result
}
}
module.exports = hooksMixin