UNPKG

@jhel/iterup

Version:

A TypeScript iterator utility library that provides lazy evaluation for efficient data processing

92 lines 3.13 kB
import { Extensions, NumericExtensions } from "./extensions"; import { range } from "./methods"; import { OverrideFunctions } from "./overrides"; import { isAsyncIterator, isIterable, isIterator } from "./utils"; /** * Sentinel value representing the absence of a value in Option types. * Used to indicate that a value should be filtered out or is not present. * * @example * ```ts * const result = someValue > 10 ? someValue * 2 : None; * ``` */ export const None = Symbol("None"); /** * Unique identifier symbol for Iterup instances. * Used internally to distinguish Iterup objects from regular iterators. */ export const IterupID = Symbol("Iterup"); /** * Creates an Iterup instance from an async iterator by wrapping it with * extension methods and overrides using a Proxy. * * @template Value - The type of values yielded by the iterator * @param iterator - The async iterator to wrap * @returns An enhanced Iterup instance with additional methods * * @internal This function is used internally by the main iterup function */ export function fromAsyncIterator(iterator) { const proxy = new Proxy(iterator, { get(target, prop, receiver) { const extension = Extensions[prop]; if (extension) { return function (...args) { return fromAsyncIterator(extension.apply(null, [target, ...args])); }; } const numericExtension = NumericExtensions[prop]; if (numericExtension) { return function (...args) { return numericExtension.apply(null, [ target, ...args, ]); }; } const value = target[prop]; if (value instanceof Function) { return function (...args) { const func = value.apply(this === receiver ? target : this, args); if (OverrideFunctions.has(prop)) { return iterup(func); } return func; }; } return value; }, }); Object.defineProperty(proxy, IterupID, {}); return proxy; } /** * Creates an Iterup instance from any iterable by converting it to an * async generator and then wrapping it. * * @template Value - The type of values in the iterable * @param array - The iterable to wrap * @returns An enhanced Iterup instance * * @internal This function is used internally by the main iterup function */ function fromIterable(array) { const iterator = async function* () { for (const value of array) { yield value; } return undefined; }; return fromAsyncIterator(iterator()); } export function iterup(collection) { if (isAsyncIterator(collection)) { return fromAsyncIterator(collection); } if (isIterator(collection) || isIterable(collection)) { return fromIterable(collection); } return fromAsyncIterator(range(collection)); } //# sourceMappingURL=core.js.map