-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback-stack.js
69 lines (58 loc) · 1.28 KB
/
callback-stack.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
/**
* @summary Stash and stack callback functions to run later.
* @locus Anywhere
* @constructor
*/
class CallbackStack {
constructor() {
this.stack = {
all: [],
};
}
store(cbStack, id = 'all') {
// init the stack if it doesn't exist
this.stack[id] = this.stack[id] || [];
// exit early
if (!cbStack) {
return false;
}
// if its a func
if (typeof(cbStack) === 'function') {
this.stack[id].push(cbStack);
// if its an array
} else if (Array.isArray(cbStack)) {
cbStack.forEach(function(func) {
this.stack[id].push(func);
});
// if its an object
} else if (typeof(cbStack) === 'object') {
Object.keys(cbStack).forEach(function(func) {
this.stack[id].push(cbStack[func]);
});
}
}
// Run a callback, or all
run(id = 'all') {
var i = 0;
// exit early if theres no cb with this id
if (!this.stack[id]) {
return false;
}
// Loop through the stack and execute each.
while (i < this.stack[id].length || i === 100) {
this.stack[id][i]();
i++;
}
// clear the stack
this.clear(id);
}
clear(id = 'all') {
this.stack[id] = [];
}
clearAll() {
this.stack = {
all: [],
};
}
}
export { CallbackStack };