-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.js
48 lines (45 loc) · 878 Bytes
/
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
var _ = require('underscore');
function stack() {
this.reset();
}
stack.prototype.reset = function() {
this.stack = [];
this.count = 0;
}
stack.prototype.add = function(item, params) {
this.stack.push({
fn: item,
params: params
});
this.count++;
}
stack.prototype.process = function(callback, async) {
var scope = this;
if (!async) {
// synchronous execution
if (this.stack.length == 0) {
callback();
return true;
}
this.stack[0].fn(this.stack[0].params,function() {
scope.stack.shift();
if (scope.stack.length == 0) {
callback();
} else {
scope.process(callback);
}
});
} else {
// asynchronous execution
var i;
for (i=0;i<this.stack.length;i++) {
this.stack[i].fn(this.stack[i].params,function() {
scope.count--;
if (scope.count == 0) {
callback();
}
});
}
}
}
exports.main = stack;