-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain-tiny.js
112 lines (101 loc) · 1.98 KB
/
chain-tiny.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*!
* chain-tiny
* Copyright(c) 2011 Kazuhito Hokamura
* MIT Licensed
*/
/**
* Constructor. Initialize Chain.
*
* @param {Function} fn
* @return {Object} chain
* @api public
*/
var Chain = function(fn) {
if (this instanceof Chain) {
this.stack = [];
return this.chain(fn);
}
else {
return new Chain(fn);
}
};
/**
* Module version
*/
Chain.version = '0.1.0';
/**
* Function push to stack.
*
* @param {Function} fn
* @return {Object} chain
* @api public
*/
Chain.prototype.chain = function(fn) {
var self = this;
if (typeof fn === 'function') {
self.stack.push(fn);
}
return self;
};
/**
* Execute all functions, in the pushed order.
*
* @param {Function} fn
* @api public
*/
Chain.prototype.end = function(fn) {
var self = this;
(function next() {
var args = Array.prototype.slice.call(arguments);
var err = args.shift() || null;
if (err || !self.stack.length) {
if (typeof fn === 'function') {
args.unshift(err);
fn.apply(null, args);
}
}
else {
args.push(next);
self.stack.shift().apply(null, args);
}
})();
};
/**
* Iterator function to each item in an array. Array recieved before next function args.
*
* @param {Function} fn
* @return {Object} chain
* @api public
*/
Chain.prototype.forEach = function(fn) {
var self = this;
return self.chain(function(ary, next) {
var _chain = Chain();
var results = [];
ary.forEach(function(val, i) {
_chain.chain(function(_next) {
fn.call(null, i, val, function(err, result) {
results.push(result);
_next(err);
});
});
});
_chain.end(function(err) {
next(err, results);
});
});
};
/**
* Iterator function to each item in an array.
*
* @param {Array} ary
* @param {Function} fn
* @return {Object} chain
* @api public
*/
Chain.forEach = function(ary, fn) {
return Chain(function(next) {
next(null, ary);
}).forEach(fn);
};
module.exports = Chain;