-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue.ts
41 lines (35 loc) · 958 Bytes
/
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
import { deferred, Deferred } from "https://deno.land/[email protected]/async/mod.ts";
export class Queue<T> {
private stopSignal: boolean;
private signal: Deferred<void>;
private queue: Array<T>;
constructor() {
this.stopSignal = false;
this.signal = deferred<void>();
this.queue = [];
}
public add(item: T) {
if (!this.stopSignal) {
this.queue.push(item);
this.signal.resolve();
}
}
public stop() {
this.stopSignal = true;
this.signal.resolve();
}
// Generator function which returns a Generator when called
public async *iterate() {
while (!this.stopSignal) {
// Sleep until any event is added to the queue
await this.signal;
// Note that while we're looping over the queue, new items may be added
for (let i = 0; i < this.queue.length && !this.stopSignal; i++) {
yield this.queue[i];
}
// Clear the queue and reset the `signal` promise
this.queue.length = 0;
this.signal = deferred();
}
}
}