-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path3-class.js
More file actions
98 lines (84 loc) · 2.02 KB
/
3-class.js
File metadata and controls
98 lines (84 loc) · 2.02 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
'use strict';
const EMPTY_CALLBACK = () => {};
class Collector {
constructor(expected) {
// number or array of string, count or keys
this.expectKeys = Array.isArray(expected) ? new Set(expected) : null;
this.expected = this.expectKeys ? expected.length : expected;
this.keys = new Set();
this.count = 0;
this.timer = null;
this.doneCallback = EMPTY_CALLBACK;
this.finished = false;
this.data = {};
}
collect(key, err, value) {
if (this.finished) return this;
if (err) {
this.finalize(err, this.data);
return this;
}
if (!this.keys.has(key)) {
this.count++;
}
this.data[key] = value;
this.keys.add(key);
if (this.expected === this.count) {
this.finalize(null, this.data);
}
return this;
}
pick(key, value) {
this.collect(key, null, value);
return this;
}
fail(key, err) {
this.collect(key, err);
return this;
}
take(key, fn, ...args) {
fn(...args, (err, data) => {
this.collect(key, err, data);
});
return this;
}
timeout(msec) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
if (msec > 0) {
this.timer = setTimeout(() => {
const err = new Error('Collector timed out');
this.finalize(err, this.data);
}, msec);
}
return this;
}
done(callback = EMPTY_CALLBACK) {
this.doneCallback = callback;
return this;
}
finalize(err, data) {
if (!this.finished) {
if (this.timer) clearTimeout(this.timer);
this.finished = true;
this.doneCallback(err, data);
}
return this;
}
}
const collect = (expected) => new Collector(expected);
// Usage
const collector = collect(3)
.timeout(1000)
.done((err, result) => {
console.dir({ err, result });
});
const sourceForKey3 = (arg1, arg2, callback) => {
console.dir({ arg1, arg2 });
callback(null, 'key3');
};
collector.collect('key1', null, 1);
collector.pick('key2', 2);
collector.take('key3', sourceForKey3, 'arg1', 'arg2');