UNPKG

evnty

Version:

Async-first, reactive event handling library for complex event flows in browser and Node.js

343 lines (342 loc) 13.4 kB
import { AnyIterable } from './types.js'; declare const enum OpKind { MAP = 0, FILTER = 1, FILTER_MAP = 2, AWAITED = 3, INSPECT = 4, ENUMERATE = 5, TAKE = 6, DROP = 7, TAKE_WHILE = 8, DROP_WHILE = 9, REDUCE = 10, FLAT_MAP = 11, EXPAND = 12 } /** * @internal * Represents a fusible operation that can be combined with other operations. */ type FusedOp = { kind: OpKind.MAP; fn: (value: unknown, index: number) => unknown; } | { kind: OpKind.FILTER; fn: (value: unknown, index: number) => unknown; } | { kind: OpKind.FILTER_MAP; fn: (value: unknown, index: number) => unknown; } | { kind: OpKind.AWAITED; } | { kind: OpKind.INSPECT; fn: (value: unknown, index: number) => unknown; } | { kind: OpKind.ENUMERATE; start: number; } | { kind: OpKind.TAKE; limit: number; } | { kind: OpKind.DROP; count: number; } | { kind: OpKind.TAKE_WHILE; fn: (value: unknown, index: number) => unknown; } | { kind: OpKind.DROP_WHILE; fn: (value: unknown, index: number) => unknown; } | { kind: OpKind.REDUCE; fn: (acc: unknown, value: unknown, index: number) => unknown; init: unknown; hasInit: boolean; } | { kind: OpKind.FLAT_MAP; fn: (value: unknown, index: number) => AsyncIterable<unknown, void, unknown>; } | { kind: OpKind.EXPAND; fn: (value: unknown, index: number) => Iterable<unknown> | Promise<Iterable<unknown>>; }; /** * A wrapper class providing functional operations on async iterables. * Enables lazy evaluation and chainable transformations on async data streams. * * Key characteristics: * - Lazy evaluation - operations are not executed until iteration begins * - Chainable - all transformation methods return new AsyncIteratorObject instances * - Supports both sync and async transformation functions * - Memory efficient - processes values one at a time * - Operation fusion - chains execute in optimized passes * * @template T The type of values yielded by the iterator * @template TReturn The return type of the iterator * @template TNext The type of value that can be passed to next() * * @example * ```typescript * // Create from an async generator * async function* numbers() { * yield 1; yield 2; yield 3; * } * * const iterator = new AsyncIteratorObject(numbers()) * .map(x => x * 2) * .filter(x => x > 2); * * for await (const value of iterator) { * console.log(value); // 4, 6 * } * ``` */ export declare class AsyncIteratorObject<T, TReturn, TNext> { /** * Creates an AsyncIteratorObject from a synchronous iterable. * Converts the sync iterable to async for uniform handling. * * @param iterable A synchronous iterable to convert * @returns A new AsyncIteratorObject wrapping the converted iterable * * @example * ```typescript * const syncArray = [1, 2, 3, 4, 5]; * const asyncIterator = AsyncIteratorObject.from(syncArray); * * for await (const value of asyncIterator) { * console.log(value); // 1, 2, 3, 4, 5 * } * ``` */ static from<T, TReturn, TNext>(iterable: Iterable<T, TReturn, TNext>): AsyncIteratorObject<T, TReturn, TNext>; /** * Merges multiple async iterables into a single stream. * Values from all sources are interleaved as they become available. * The merged iterator completes when all source iterators complete. * * @param iterables The async iterables to merge * @returns A new AsyncIteratorObject yielding values from all sources * * @example * ```typescript * async function* source1() { yield 1; yield 3; } * async function* source2() { yield 2; yield 4; } * * const merged = AsyncIteratorObject.merge(source1(), source2()); * * for await (const value of merged) { * console.log(value); // Order depends on timing: 1, 2, 3, 4 or similar * } * ``` */ static merge<T>(...iterables: AsyncIterable<T, void, unknown>[]): AsyncIteratorObject<T, void, unknown>; /** @internal */ iterable: AsyncIterable<unknown, unknown, unknown>; /** @internal */ parent: AsyncIteratorObject<unknown, unknown, unknown> | null; /** @internal */ op: FusedOp | null; /** @internal */ cachedOps: FusedOp[] | null; readonly [Symbol.toStringTag] = "AsyncIteratorObject"; constructor(iterable: AsyncIterable<T, TReturn, TNext>, parent?: AsyncIteratorObject<unknown, unknown, unknown> | null, op?: FusedOp | null); /** * Escape hatch for custom transformations not covered by the built-in operators. * Materializes the fused operation chain, then applies a generator function to each value. * * @param generatorFactory A function that returns a generator function for transforming values * @param signal Optional AbortSignal to cancel the operation * @returns A new AsyncIteratorObject with transformed values */ pipe<U>(generatorFactory: () => (value: T) => AnyIterable<U, void, unknown>, signal?: AbortSignal): AsyncIteratorObject<U, void, unknown>; /** * Resolves promise-like values from the source iterator. * Useful for normalizing values before applying type-guard predicates. * * @returns A new AsyncIteratorObject yielding awaited values */ awaited(): AsyncIteratorObject<Awaited<T>, void, unknown>; /** * Transforms each value using a mapping function. * The callback can be synchronous or return a promise. * * @param callbackfn Function to transform each value * @returns A new AsyncIteratorObject yielding transformed values * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3]); * const doubled = numbers.map(x => x * 2); * * for await (const value of doubled) { * console.log(value); // 2, 4, 6 * } * ``` */ map<U>(callbackfn: (value: T, index: number) => U): AsyncIteratorObject<U, void, unknown>; /** * Filters values based on a predicate function. * Only values for which the predicate returns truthy are yielded. * Supports type guard predicates for type narrowing. * * @param predicate Function to test each value * @returns A new AsyncIteratorObject yielding only values that pass the test * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3, 4, 5]); * const evens = numbers.filter(x => x % 2 === 0); * * for await (const value of evens) { * console.log(value); // 2, 4 * } * ``` */ filter(predicate: (value: T, index: number) => unknown): AsyncIteratorObject<T, void, unknown>; filter<S extends T>(predicate: (value: T, index: number) => value is S): AsyncIteratorObject<S, void, unknown>; /** * Combined filter and map operation. Returns undefined to skip a value. * The callback result is awaited to check for undefined. * * @param callbackfn Function that returns a transformed value or undefined to skip * @returns A new AsyncIteratorObject yielding non-undefined transformed values * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3, 4, 5]); * const doubledEvens = numbers.filterMap(x => x % 2 === 0 ? x * 2 : undefined); * * for await (const value of doubledEvens) { * console.log(value); // 4, 8 * } * ``` */ filterMap<U>(callbackfn: (value: T, index: number) => U): AsyncIteratorObject<Exclude<Awaited<U>, undefined>, void, unknown>; /** * Executes a side-effect function for each value without modifying the stream. * Useful for debugging or logging. The callback is awaited for proper sequencing. * * @param callbackfn Function to execute for each value * @returns A new AsyncIteratorObject yielding the same values * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3]); * const logged = numbers.inspect(x => console.log('value:', x)).map(x => x * 2); * ``` */ inspect(callbackfn: (value: T, index: number) => unknown): AsyncIteratorObject<T, TReturn, TNext>; /** * Wraps each value with its index as a tuple. * Useful after filtering when original indices are lost. * * @param start Starting index (default: 0) * @returns A new AsyncIteratorObject yielding [index, value] tuples * * @example * ```typescript * const letters = AsyncIteratorObject.from(['a', 'b', 'c']); * const enumerated = letters.enumerate(); * * for await (const [i, v] of enumerated) { * console.log(i, v); // 0 'a', 1 'b', 2 'c' * } * ``` */ enumerate(start?: number): AsyncIteratorObject<[number, T], void, unknown>; /** * Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached. * @param limit The maximum number of values to yield. */ take(limit: number): AsyncIteratorObject<T, void, unknown>; /** * Takes values while the predicate returns truthy. * Stops immediately when predicate returns falsy. * Supports type guard predicates for type narrowing. * * @param predicate Function to test each value * @returns A new AsyncIteratorObject yielding values until predicate fails * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3, 4, 5]); * const small = numbers.takeWhile(x => x < 4); * * for await (const value of small) { * console.log(value); // 1, 2, 3 * } * ``` */ takeWhile(predicate: (value: T, index: number) => unknown): AsyncIteratorObject<T, void, unknown>; takeWhile<S extends T>(predicate: (value: T, index: number) => value is S): AsyncIteratorObject<S, void, unknown>; /** * Creates an iterator whose values are the values from this iterator after skipping the provided count. * @param count The number of values to drop. */ drop(count: number): AsyncIteratorObject<T, void, unknown>; /** * Skips values while the predicate returns truthy. * Yields all remaining values once predicate returns falsy. * * @param predicate Function to test each value * @returns A new AsyncIteratorObject skipping values until predicate fails * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3, 4, 5]); * const afterSmall = numbers.dropWhile(x => x < 3); * * for await (const value of afterSmall) { * console.log(value); // 3, 4, 5 * } * ``` */ dropWhile(predicate: (value: T, index: number) => unknown): AsyncIteratorObject<T, void, unknown>; /** * Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables. * @param callback A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result. */ flatMap<U>(callback: (value: T, index: number) => AsyncIterable<U, void, unknown>): AsyncIteratorObject<U, void, unknown>; /** * Creates an iterator of accumulated values by applying a reducer function. * Unlike Array.reduce, this returns an iterator that yields each intermediate accumulated value, * not just the final result. This allows observing the accumulation process. * * @param callbackfn Reducer function to accumulate values * @param initialValue Optional initial value for the accumulation * @returns A new AsyncIteratorObject yielding accumulated values at each step * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3, 4]); * const sums = numbers.reduce((sum, x) => sum + x, 0); * * for await (const value of sums) { * console.log(value); // 1, 3, 6, 10 (running totals) * } * ``` */ reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): AsyncIteratorObject<T, void, unknown>; reduce<R>(callbackfn: (previousValue: R, currentValue: T, currentIndex: number) => R, initialValue: R): AsyncIteratorObject<R, void, unknown>; /** * Transforms each value into multiple values using an expander function. * Each input value is expanded into zero or more output values. * Like `flatMap` but takes sync Iterables (or Promises of Iterables) instead of AsyncIterables. * * @param callbackfn Function that returns an iterable of values for each input * @returns A new AsyncIteratorObject yielding all expanded values * * @example * ```typescript * const numbers = AsyncIteratorObject.from([1, 2, 3]); * const expanded = numbers.expand(x => [x, x * 10]); * * for await (const value of expanded) { * console.log(value); // 1, 10, 2, 20, 3, 30 * } * ``` */ expand<U>(callbackfn: (value: T, index: number) => Promise<Iterable<U>> | Iterable<U>): AsyncIteratorObject<U, void, unknown>; [Symbol.asyncIterator](): AsyncIterator<T, TReturn, TNext>; } export {};