-
Notifications
You must be signed in to change notification settings - Fork 0
/
race.js
37 lines (32 loc) · 820 Bytes
/
race.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
//let's use few lib, simulate async.race or promise.race
const once = (func) => {
let run = false;
return (...args) => {
if (run) {
return;
}
run = true;
return func.apply(null, args);
};
};
const callbackOncePass = (maxCall, callback) => {
let num = 0;
return (err, result) => {
if (++num >= maxCall) {
return callback(err, result);
} else if (!err) {
return callback(err, result);
}
};
};
const race = (array, func, callback) => {
const length = array.length;
if (length === 0) {
return callback();
}
const onceCallback = once(callback);
for (const item of array) {
func.call(null, item, callbackOncePass(length, onceCallback));
}
};
module.exports = race;