Forked from n1ru4l/makePushPullAsyncIterableIterator.ts
Created
January 13, 2021 03:22
-
-
Save maraisr/9b2185a297eba6c082771090c8a22ba2 to your computer and use it in GitHub Desktop.
Without using Symbol.asyncIterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Deferred<T> = { | |
resolve: (value: T) => void; | |
reject: (value: unknown) => void; | |
promise: Promise<T>; | |
}; | |
function createDeferred<T>(): Deferred<T> { | |
const d = {} as Deferred<T>; | |
d.promise = new Promise<T>((resolve, reject) => { | |
d.resolve = resolve; | |
d.reject = reject; | |
}); | |
return d; | |
} | |
export function makePushPullAsyncIterableIterator<T>() { | |
let isRunning = true; | |
const pushQueue: Array<T> = []; | |
let d = createDeferred<"FINISH" | "NEW_VALUE">(); | |
const iterator = (async function* PushPullAsyncIterableIterator(): AsyncIterableIterator< | |
T | |
> { | |
while (true) { | |
if (pushQueue.length > 0) { | |
yield pushQueue.shift()!; | |
} else { | |
const res = await d.promise; | |
if (res === "FINISH") { | |
return; | |
} | |
} | |
} | |
})(); | |
function push(value: T) { | |
if (isRunning === false) { | |
// TODO: Should this throw? | |
return; | |
} | |
pushQueue.push(value); | |
d.resolve("NEW_VALUE"); | |
d = createDeferred(); | |
} | |
const oReturn = iterator["return"]?.bind(iterator); | |
iterator["return"] = (...args) => { | |
d.resolve("FINISH"); | |
return ( | |
oReturn?.(...args) ?? Promise.resolve({ done: true, value: undefined }) | |
); | |
}; | |
return [push, iterator] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment