-
Notifications
You must be signed in to change notification settings - Fork 4
/
queue.ts
60 lines (52 loc) · 1.6 KB
/
queue.ts
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
/**
* Queue for actions to be performed with a limited concurrency.
*/
export class ActionQueue<T> {
action: (e: T) => Promise<any>;
parallelism: number;
pendingQueue: Array<T> = [];
running = 0;
constructor(parallelism: number, action: (e: T) => Promise<any>) {
this.parallelism = parallelism;
this.action = action;
}
push(e: T) {
this.pendingQueue.push(e);
this.trigger();
}
trigger() {
while (this.running < this.parallelism && this.pendingQueue.length) {
const element = this.pendingQueue.shift();
this.running++;
Promise.resolve(this.action(element)).finally(() => {
this.running--;
this.trigger();
});
}
}
}
/**
* Queue for items occurring together in time to be grouped into batches.
*/
export class BufferedQueue<T> {
duration: number;
currentBatch: Array<T> = [];
currentBatchTimeout: NodeJS.Timeout;
batchConsumer: (batch: Array<T>) => Promise<any>;
constructor(duration: number, batchConsumer: (batch: Array<T>) => Promise<any>) {
this.duration = duration;
this.batchConsumer = batchConsumer;
}
push(e: T) {
this.currentBatch.push(e);
if (this.currentBatchTimeout) {
clearTimeout(this.currentBatchTimeout);
}
this.currentBatchTimeout = setTimeout(this.finalizeBatch.bind(this), this.duration)
}
finalizeBatch() {
this.batchConsumer(this.currentBatch)
this.currentBatch = [];
clearTimeout(this.currentBatchTimeout);
}
}