-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-queue.ts
50 lines (37 loc) · 1.13 KB
/
async-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
export class AsyncQueue<T> implements AsyncIterator<T>
{
#reads: (({}: IteratorResult<T>) => void)[] = [];
#writes: [() => void, T][] = [];
next(): Promise<IteratorResult<T>>
{
return new Promise(resolve => {
this.#reads.push(resolve);
this.#flush();
});
}
push(value: T): Promise<void>
{
return new Promise(resolve => {
this.#writes.push([resolve, value]);
this.#flush();
});
}
end() {
for (const resolve of this.#reads)
resolve({value: undefined, done: true});
this.#reads = [];
for (const [resolve] of this.#writes)
resolve();
this.#writes = [];
}
[Symbol.asyncIterator](): AsyncIterator<T> { return this; }
#flush() {
let count = Math.min(this.#reads.length, this.#writes.length);
while (count--) {
const resolveRead = this.#reads.shift()!;
const [resolveWrite, value] = this.#writes.shift()!;
resolveRead({value, done: false});
resolveWrite();
}
}
}