-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathDefer.js
98 lines (94 loc) · 2.86 KB
/
Defer.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
function Defer() {
if (!(this instanceof Defer)) {
return new Defer();
}
this.resolved = false;
this.resolveValue = null;
this.cb = null;
}
Defer.prototype = {
resolve: function (value) {
this.resolved = true;
this.resolveValue = value;
if (this.cb) {
_.forEach(this.cb, function (cb) {
this.resolveValue = cb(this.resolveValue) || this.resolveValue;
}, this);
}
return this;
},
//could be synchronous if already resolved!
done: function (cb) {
if (this.resolved) {
this.resolveValue = cb(this.resolveValue) || this.resolveValue;
} else {
if (!this.cb) {
this.cb = [cb];
} else {
this.cb.push(cb);
}
}
return this;
}
};
Defer.allDone = function (values, eachDone) {
var startingIndex;
values = values.slice();
if (_.isArray(values)) {
startingIndex = values.length;
for (var i = values.length - 1; i >= 0; i--) {
if (values[i] instanceof Defer) {
if (values[i].resolved) {
startingIndex = i;
if (_.isArray(values[i].resolveValue)) {
values.splice.apply(values, [i, 1].concat(values[i].resolveValue));
} else {
values[i] = values[i].resolveValue
}
} else {
(function (startingIndex) {
values.splice(i, 1)[0].done(function (val) {
val = _.isArray(val) ? val : [val];
eachDone(val, startingIndex);
});
}(i));
}
} else {
startingIndex = i;
}
}
eachDone(values, startingIndex);
} else {
if (values instanceof Defer) {
values.done(eachDone);
} else {
eachDone(values);
}
}
};
Defer.eachDone = function (value, eachDone) {
if (_.isArray(value)) {
_.forEach(value, function (value, index) {
if (value instanceof Defer) {
value.done(function (value) {
if (_.isArray(value)) {
_.each(value, function (value, i, list) {
var addedIndex = (i + 1) / (list.length + 2);
eachDone(value, index + addedIndex);
});
} else {
eachDone(value, index);
}
});
} else {
eachDone(value, index);
}
});
} else {
if (value instanceof Defer) {
value.done(eachDone);
} else {
eachDone(value);
}
}
};