1
0
Files
sequence-js/src/utils.ts

66 lines
1.6 KiB
TypeScript

export type Nullable<T> = T | null | undefined;
export function isDefined<T = any>(obj: T): obj is NonNullable<T> {
return obj !== undefined && obj !== null;
}
export function isAsyncIterable<T = any>(obj: any): obj is AsyncIterable<T> {
return isDefined(obj) && typeof obj[Symbol.asyncIterator] === "function";
}
export function asArray<T>(iterable: Iterable<T>) {
return Array.isArray(iterable) ? <T[]>iterable : Array.from(iterable);
}
export function identity<T>(obj: T) {
return obj;
}
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;
}
type FindElementSuccess<T> = {
found: true;
element: T;
};
type FindElementFail = {
found: false;
reason?: number;
};
export type FindElementResult<T> = FindElementSuccess<T> | FindElementFail;