Last active
February 28, 2019 10:52
-
-
Save krotscheck/8c95ccceb82fc07b795248cc0f308b6b to your computer and use it in GitHub Desktop.
Concatenate any kind of iterable or iterator in typescript
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
export type IterableOrIterator<T> = Iterable<T> | Iterator<T> | AsyncIterable<T> | AsyncIterator<T>; | |
/** | |
* Concatenate any kind of iterable. | |
*/ | |
export async function* concatIterable<T>(...iterators: IterableOrIterator<T>[]) { | |
for (let i of iterators) { | |
if (isIterable(i)) { | |
i = i[Symbol.iterator](); | |
} else if (isAsyncIterable(i)) { | |
i = i[Symbol.asyncIterator](); | |
} | |
let f: IteratorResult<T> | Promise<IteratorResult<T>>; | |
while (true) { | |
f = i.next(); | |
if (isPromiseLike(f)) { | |
f = await f; | |
} | |
if (f.done) { | |
break; | |
} | |
yield f.value; | |
} | |
} | |
} | |
function isPromiseLike<T>(object: any): object is Promise<T> { | |
return object && 'then' in object && typeof object.then === 'function'; | |
} | |
function isIterable<T>(object: any): object is Iterable<T> { | |
return object && Symbol.iterator in object; | |
} | |
function isAsyncIterable<T>(object: any): object is AsyncIterable<T> { | |
return object && Symbol.asyncIterator in object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment