-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
57 lines (52 loc) · 1.13 KB
/
index.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var logUpdate = require("log-update");
var toX = () => "X";
var delay = (seconds) =>
new Promise((resolves) => {
setTimeout(resolves, seconds * 1000);
});
var tasks = [
delay(4),
delay(6),
delay(4),
delay(3),
delay(5),
delay(7),
delay(9),
delay(10),
delay(3),
delay(5),
];
class PromiseQueue {
constructor(promises = [], concurrentCount = 1) {
this.concurrent = concurrentCount;
this.total = promises.length;
this.todo = promises;
this.running = [];
this.complete = [];
}
get runAnother() {
return this.running.length < this.concurrent && this.todo.length;
}
grabTasks() {
var { todo, running, complete } = this;
logUpdate(`
todo: [${todo.map(toX)}]
running: [${running.map(toX)}]
complete: [${complete.map(toX)}]
`);
}
run() {
while (this.runAnother) {
var promise = this.todo.shift();
promise.then(() => {
this.complete.push(this.running.shift());
this.grabTasks();
this.run();
});
this.running.push(promise);
this.grabTasks();
}
}
}
var delayQueue = new PromiseQueue(tasks, 2);
delayQueue.run();