-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhooks-dict.js
47 lines (45 loc) · 1.53 KB
/
hooks-dict.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
import { _ } from 'meteor/underscore';
import { Dict } from './dict.js';
export class HooksDict extends Dict {
/**
* Add a function to a group of hooks
* @param {String} key a valid key string for a group of hooks
* @param {Function} fn a function to add to the group of hooks
*/
add(key, fn) {
// check arguments
if (!_.isString(key)) throw Error('hooksDict.add: first argument must be a String.');
if (!_.isFunction(fn)) throw Error('hooksDict.add: second argument must be a Function.');
// if the group of hooks does not exist, setup it
if (!_.isArray(this.pairs[key])) this._setup(key);
// add the function to the group
this.pairs[key].push(fn);
}
// runs a group of hooks
run(key, data) {
// if key is not found return data
if(!this.pairs[key]) return data;
// if key exists get the array of functions
const hooks = this.get(key);
// iterate with all functions
return hooks.reduce(function(result, hook) {
if (_.isUndefined(result)) throw new Error('hooksDict.run: all functions must return something!');
return hook(result);
}, data);
}
// setup a group of hooks
_setup(key) {
this.pairs[key] = [];
}
// check if a value is a function
_checkValue(value) {
if (!_.isArray(value)) {
throw new Error('hooksDict._checkValue: must provide only Array as values.');
}
_.each(value, (el) => {
if (!_.isFunction(el)) {
throw new Error('hooksDict._checkValue: must provide only Function as array elements.');
}
});
}
}