Last active
November 24, 2020 17:59
-
-
Save jed/cc1e949419d42e2cb26d7f2e1645864d to your computer and use it in GitHub Desktop.
Teeing an asynchronous iterator
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
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