Skip to content

Instantly share code, notes, and snippets.

@jed

jed/tee.js

Last active Nov 24, 2020
Embed
What would you like to do?
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