-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
56 lines (45 loc) · 1.22 KB
/
index.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
var nextTick = function (fn) {
if (typeof setImmediate === 'function')
setImmediate(fn);
else if (typeof process !== 'undefined' && process.nextTick)
process.nextTick(fn);
else
setTimeout(fn, 0);
};
var makeIterator = function (tasks) {
var makeCallback = function (index) {
var fn = function () {
if (tasks.length)
tasks[index].apply(null, arguments);
return fn.next();
};
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
};
return makeCallback(0);
};
var _isArray = Array.isArray || function(maybeArray){
return Object.prototype.toString.call(maybeArray) === '[object Array]';
};
var waterfall = function (tasks, callback) {
callback = callback || function () {};
if (!_isArray(tasks)) { return callback (); }
if (!tasks.length) { return callback (); }
var wrapIterator = function (iterator) {
return function (err) {
var args = Array.prototype.slice.call(arguments);
var next = iterator.next();
if (next)
args.push (wrapIterator (next));
else
args.push (callback);
nextTick(function () {
iterator.apply(null, args);
});
};
};
wrapIterator(makeIterator(tasks))();
};
exports = module.exports = waterfall;