-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
65 lines (58 loc) · 1.42 KB
/
mod.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
61
62
63
64
65
export type Factory<T> = (
emit: (t: T) => unknown,
done: () => unknown,
) => unknown;
function makeDeferral<T = void>() {
let resolve: (t: T) => unknown;
const promise = new Promise<T>((_res) => {
resolve = _res;
});
// @ts-ignore: resolve is not used before it is defined since the code above runs synchronously
return [resolve, promise] as const;
}
async function defer() {
const [resolve, promise] = makeDeferral();
resolve();
return promise;
}
/**
* Given a factory function, creates an asynchronous iterator which emits items passed to its
* callback.
*/
export default async function* listenator<T>(factory: Factory<T>) {
// Set up iterator state
const queue: Array<T> = [];
let done = false;
let [resolve, prom] = makeDeferral();
// Call the factory function with state modifying functions
factory(
// emit
(t: T) => {
if (done) {
return;
}
queue.push(t);
resolve();
},
// done
() => {
done = true;
resolve();
},
);
// Asynchronous iterator loop
while (true) {
await prom;
// Flush all queued values
while (queue.length > 0) {
yield queue.shift();
await defer();
}
// At this point the queue is empty, should we complete the iterator?
if (done) {
break;
}
// If we aren't done yet, set up `resolve` and `prom` for the next value
[resolve, prom] = makeDeferral();
}
}