-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path9-build.js
More file actions
72 lines (65 loc) · 1.5 KB
/
9-build.js
File metadata and controls
72 lines (65 loc) · 1.5 KB
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
'use strict';
const metasync = require('metasync');
const async = (op) => {
switch (op) {
case 'map':
return metasync.map;
case 'filter':
return metasync.filter;
case 'reduce':
return metasync.reduce;
case 'each':
return metasync.each;
case 'series':
return metasync.series;
case 'find':
return metasync.find;
default:
return null;
}
};
function ArrayChain(array) {
this.array = array;
this.chain = [];
}
ArrayChain.prototype.execute = function (err) {
const item = this.chain.shift() || {};
if (err) {
if (!item.op) throw err;
if (item.op === 'catch') {
item.fn(err);
return void this.execute();
} else {
return void this.execute(err);
}
}
if (!item.op) return;
if (item.op === 'then') {
item.fn(this.array);
return void this.execute();
}
const op = async(item.op);
if (!op) return void this.execute();
op(this.array, item.fn, (err, data) => {
if (err) return void this.execute(err);
this.array = data;
this.execute();
});
};
['then', 'catch', 'map', 'filter', 'reduce', 'each', 'series', 'find'].map(
(op) => {
ArrayChain.prototype[op] = function (fn) {
this.chain.push({ op, fn });
return this;
};
},
);
ArrayChain.prototype.fetch = function (fn) {
this.chain.push({ op: 'then', fn: (res) => fn(null, res) });
this.chain.push({ op: 'catch', fn });
this.execute();
return this;
};
module.exports = {
for: (array) => new ArrayChain(array),
};