Created
March 26, 2023 17:07
-
-
Save JamieMason/23025f64f3284f89389823e5f1a48887 to your computer and use it in GitHub Desktop.
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 GetFn = () => { | |
next(iteration: IteratorResult<any, any>): IteratorResult<any, any>; | |
}; | |
function iterateOverSyncOrAsyncGenerator<T extends Iterable<any>>(getIterator: GetFn, gen: T): Iterable<any>; | |
function iterateOverSyncOrAsyncGenerator<T extends AsyncIterable<any>>(getIterator: GetFn, gen: T): AsyncIterable<any>; | |
function iterateOverSyncOrAsyncGenerator<T extends Iterable<any> | AsyncIterable<any>>( | |
getIterator: GetFn, | |
gen: T | |
): Iterable<any> | AsyncIterable<any> { | |
if (Symbol.asyncIterator in gen) { | |
const iterator = getIterator(); | |
return { | |
[Symbol.asyncIterator]() { | |
const genIterator = gen[Symbol.asyncIterator](); | |
return { | |
async next(...args) { | |
const iteration = await genIterator.next(...args); | |
console.log('async', args, '->', iteration); | |
return iterator.next(iteration); | |
}, | |
}; | |
}, | |
}; | |
} | |
if (Symbol.iterator in gen) { | |
const iterator = getIterator(); | |
return { | |
[Symbol.iterator]() { | |
const genIterator = gen[Symbol.iterator](); | |
return { | |
next(...args) { | |
const iteration = genIterator.next(...args); | |
console.log('sync', args, '->', iteration); | |
return iterator.next(iteration); | |
}, | |
}; | |
}, | |
}; | |
} | |
throw new Error('Value is not an iterator or asyncIterator'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment