refactor
This commit is contained in:
64
src/utils.ts
64
src/utils.ts
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user