-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path8-prototype.js
More file actions
103 lines (89 loc) · 2.11 KB
/
8-prototype.js
File metadata and controls
103 lines (89 loc) · 2.11 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
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
'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();
});
};
ArrayChain.prototype.then = function (fn) {
this.chain.push({ op: 'then', fn });
return this;
};
ArrayChain.prototype.catch = function (fn) {
this.chain.push({ op: 'catch', 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;
};
ArrayChain.prototype.map = function (fn) {
this.chain.push({ op: 'map', fn });
return this;
};
ArrayChain.prototype.filter = function (fn) {
this.chain.push({ op: 'filter', fn });
return this;
};
ArrayChain.prototype.reduce = function (fn) {
this.chain.push({ op: 'reduce', fn });
return this;
};
ArrayChain.prototype.each = function (fn) {
this.chain.push({ op: 'each', fn });
return this;
};
ArrayChain.prototype.series = function (fn) {
this.chain.push({ op: 'series', fn });
return this;
};
ArrayChain.prototype.find = function (fn) {
this.chain.push({ op: 'find', fn });
return this;
};
module.exports = {
for: (array) => new ArrayChain(array),
};