-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy patha-collector.js
More file actions
63 lines (51 loc) · 1.15 KB
/
a-collector.js
File metadata and controls
63 lines (51 loc) · 1.15 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
'use strict';
function Collector() {}
const collect = (expected) => {
const collector = (key, value) => {
if (collector.finished) return collector;
collector.count++;
collector.data[key] = value;
if (value instanceof Error) {
collector.callback(value, collector.data);
return collector;
}
if (collector.expected === collector.count) {
collector.finished = true;
collector.callback(null, collector.data);
}
return collector;
};
const fields = {
count: 0,
expected,
data: {},
callback: null,
finished: false
};
Object.setPrototypeOf(collector, Collector.prototype);
return Object.assign(collector, fields);
};
Collector.prototype.done = function(callback) {
this.callback = callback;
return this;
};
// Usage
const dc = collect(4).done((err, data) => {
console.log('Done callback ');
console.dir({ err, data });
});
dc('key1', 'value1');
setTimeout(() => {
dc('key2', 'value2');
}, 100);
setImmediate(() => {
dc('key3', 'value3');
});
dc('key4', 'value4');
dc('key5', 'value5');
// {
// key1: 'value1',
// key4: 'value4',
// key5: 'value5',
// key3: 'value3'
// }