Skip to content

Commit f96d06f

Browse files
add: Throttle Queue
1 parent a8da3c7 commit f96d06f

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@
66
- [Fixing setting up a callback](fixing-setting-up-a-callback)
77
- [Getting the distinct transactions](getting-the-distinct-transactions)
88
- [Replacing with the cipher letters](replacing-with-the-cipher-letters)
9+
- [Throttle Queue](throttle-queue)
910
- [Validating a maze path](validating-a-maze-path)

throttle-queue/README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Throttle Queue
2+
3+
Build an app that runs no more than `n` queue functions at once.
4+
5+
- Run up to N functions in the Queue
6+
- When one (each) completes, run another if there are any
7+
- When ALL functions in queue are resolved, return the results array
8+
9+
## Execute
10+
11+
```bash
12+
node solution.js
13+
```

throttle-queue/solution.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
function getRandomInt(max) {
2+
return Math.floor(Math.random() * max);
3+
}
4+
5+
let i = 0;
6+
7+
function returnSlow() {
8+
return new Promise((resolve) => {
9+
const myI = i;
10+
i++;
11+
console.log('started ' + myI);
12+
setTimeout(() => {
13+
console.log('ended ' + myI);
14+
resolve(getRandomInt(10));
15+
}, getRandomInt(8) * 100 + 200);
16+
});
17+
}
18+
19+
function throttle1(queue, acc) {
20+
if (queue.length) {
21+
const fn = queue.shift();
22+
return fn().then((result) => {
23+
// I have result and rest of queue
24+
const resultAcc = acc || [];
25+
resultAcc.push(result);
26+
27+
if (!queue.length) return resultAcc;
28+
return throttle1(queue, resultAcc);
29+
});
30+
}
31+
}
32+
33+
function throttleQ(queue, n, result) {
34+
let subQueue = [];
35+
36+
while (queue.length && subQueue.length < n) {
37+
subQueue.push(queue.shift());
38+
}
39+
40+
return Promise.all(subQueue.map((fn) => fn())).then(
41+
(subResult) => {
42+
const resultAcc = [...(result ?? []), ...subResult];
43+
return queue.length
44+
? throttleQ(queue, n, resultAcc)
45+
: resultAcc;
46+
},
47+
);
48+
}
49+
50+
(async () => {
51+
const fns = [...Array(25)].map((_, i) =>
52+
returnSlow.bind(null, i),
53+
);
54+
55+
const promises = await throttleQ(fns, 6);
56+
57+
const data = await Promise.all(promises);
58+
59+
console.log({ data });
60+
})();

0 commit comments

Comments
 (0)