Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created March 26, 2023 17:07
Show Gist options
  • Save JamieMason/23025f64f3284f89389823e5f1a48887 to your computer and use it in GitHub Desktop.
Save JamieMason/23025f64f3284f89389823e5f1a48887 to your computer and use it in GitHub Desktop.
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