Skip to content

Instantly share code, notes, and snippets.

@jed
Last active November 24, 2020 17:59
Show Gist options
  • Save jed/cc1e949419d42e2cb26d7f2e1645864d to your computer and use it in GitHub Desktop.
Save jed/cc1e949419d42e2cb26d7f2e1645864d to your computer and use it in GitHub Desktop.
Teeing an asynchronous iterator
function tee(asyncIterable) {
let source = asyncIterable[Symbol.asyncIterator]()
return [[], []].map((buffer, i, buffers) => ({
async next() {
if (0 in buffer) return buffer.shift()
let item = await source.next()
if (!item.done) buffers[1 - i].push(item)
return item
},
[Symbol.asyncIterator]() {
return this
}
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment