1
0
This commit is contained in:
2024-05-18 15:07:08 +02:00
parent 8c6693ad98
commit 654151e06e
5 changed files with 69 additions and 58 deletions

View File

@@ -70,30 +70,6 @@ export function reverseAsyncComparer<T>(comparer: MaybeAsyncComparer<T>): AsyncC
return async (a, b) => await comparer(b, a);
}
export function* asGenerator<T>(iterator: Iterator<T>) {
while (true) {
const next = iterator.next();
if (next.done) {
return next.value;
}
yield next.value;
}
}
export async function* asAsyncGenerator<T>(iterator: MaybeAsyncIterator<T>) {
while (true) {
const next = await iterator.next();
if (next.done) {
return next.value;
}
yield next.value;
}
}
export function asArray<T>(iterable: Iterable<T>) {
return Array.isArray(iterable) ? <T[]>iterable : Array.from(iterable);
}
@@ -110,6 +86,44 @@ class WrappedIterator<T> implements Iterable<T> {
}
}
export function wrapAsIterable<T>(iterator: Iterator<T>): Iterable<T> {
export function asIterable<T>(iterator: Iterator<T>): Iterable<T> {
return isIterable<T>(iterator) ? iterator : new WrappedIterator(iterator);
}
class WrappedAsyncIterator<T> implements AsyncIterable<T> {
readonly #iterator: AsyncIterator<T>;
constructor(iterator: AsyncIterator<T>) {
this.#iterator = iterator;
}
[Symbol.asyncIterator]() {
return this.#iterator;
}
}
export function asAsyncIterable<T>(iterator: AsyncIterator<T>): AsyncIterable<T> {
return isAsyncIterable<T>(iterator) ? iterator : new WrappedAsyncIterator(iterator);
}
const _emptyIterableIterator = new class EmptyIterableIterator implements IterableIterator<any> {
[Symbol.iterator]() {
return this;
}
next(): IteratorResult<any, any> {
return { done: true, value: undefined };
}
return(value?: any): IteratorResult<any, any> {
throw new Error("Method not implemented.");
}
throw(e?: any): IteratorResult<any, any> {
throw new Error("Method not implemented.");
}
}
export function emptyIterableIterator<T>(): IterableIterator<T> {
return _emptyIterableIterator;
}