-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
57 lines (46 loc) · 1.23 KB
/
solution.js
File metadata and controls
57 lines (46 loc) · 1.23 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
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let i = 0;
function returnSlow() {
return new Promise((resolve) => {
const myI = i;
i++;
console.log('started ' + myI);
setTimeout(
() => {
console.log('ended ' + myI);
resolve(getRandomInt(10));
},
getRandomInt(8) * 100 + 200,
);
});
}
function throttle1(queue, acc) {
if (queue.length) {
const fn = queue.shift();
return fn().then((result) => {
// I have result and rest of queue
const resultAcc = acc || [];
resultAcc.push(result);
if (!queue.length) return resultAcc;
return throttle1(queue, resultAcc);
});
}
}
function throttleQ(queue, n, result) {
let subQueue = [];
while (queue.length && subQueue.length < n) {
subQueue.push(queue.shift());
}
return Promise.all(subQueue.map((fn) => fn())).then((subResult) => {
const resultAcc = [...(result ?? []), ...subResult];
return queue.length ? throttleQ(queue, n, resultAcc) : resultAcc;
});
}
(async () => {
const fns = [...Array(25)].map((_, i) => returnSlow.bind(null, i));
const promises = await throttleQ(fns, 6);
const data = await Promise.all(promises);
console.log({ data });
})();