iterates
Version:
Iterator and AsyncIterator helper functions with typings
413 lines • 14.7 kB
TypeScript
import { IterableOrIterator } from './sync.js';
export declare type Awaitable<T> = T | PromiseLike<T>;
/**
* Either an AsyncIterable or an AsyncIterator
*/
export declare type AsyncIterableOrIterator<T> = AsyncIterable<Awaitable<T>> | AsyncIterator<Awaitable<T>>;
/** @internal */
export declare type AnyIterableOrIterator<T> = IterableOrIterator<T> | AsyncIterableOrIterator<T>;
/** @internal */
export declare const isIterator: (iterator: any) => iterator is AsyncIterator<unknown, any, undefined>;
/** @internal */
export declare const asIterable: <T>(asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterable<T>;
/**
* Turns a syncronous Iterable or Iterator to an asyncronous Iterable.
*/
export declare function asAsyncIterable<T>(iterator: IterableOrIterator<T>): AsyncIterable<T>;
/**
* Collect all values of the iterator in an Array.
*/
export declare function asArray<T>(iterator: AsyncIterableOrIterator<T>): Promise<Array<T>>;
/**
* Creates in iterable that yields and then ends when the promise resolves
*/
export declare function fromPromise<T>(promise: Promise<T>): AsyncIterableIterator<T>;
export interface ISubject<T, E = any> extends AsyncIterable<T> {
/**
* Push an item into the subject to yield to iterators
*/
next(item: T): void;
/**
* Throw an error to the iterators
*/
throw(err: E): void;
/**
* Ends the iterators
*
* Efter calling done the Subject is dispased and can no longer be used
*/
done(): void;
}
/**
* A Subject is an AsyncIterable which yields values that are pushed to the Subject.
*
* The Subject can be seen as an EventEmitter, allowing a producer to
* push values to one or more consumers
*
* ## Example
* ```typescript
* const timestamps = new Subject<Date>()
*
* setInterval(() => timestamps.next(new Date()), 1000)
*
* for await (const timestamp of timestamps) {
* console.log(timestamp); // Will log the current time every second
* }
* ```
*/
export declare class Subject<T, E = any> implements ISubject<T, E> {
private _subscribers;
private _isDisposed;
private _checkDisposed;
/**
* Push an item into the subject to yield to iterators
*/
next(item: T): void;
/**
* Throw an error to the iterators
*/
throw(error: E): void;
/**
* Ends the iterators
*
* Efter calling done the Subject is dispased and can no longer be used
*/
done(): void;
[Symbol.asyncIterator](): AsyncIterator<T, any, undefined>;
}
/**
* Creates an iterator which gives the current iteration count
* as well as the next value.
*
* The iterator returned yields objects of {index, item}, where index is the
* current index of iteration and item is the value returned by the iterator.
*
* ## Example
* ```typescript
* [...enumerate(['a', 'b', 'c'])]
* // [{index: 0, item: 'a'}, {index: 1, item: 'b'}, {index: 2, item: 'c'}]
* ```
*/
export declare function enumerate<T>(asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<{
index: number;
item: T;
}>;
/**
* Calls fn for every item in the iterator to produce an iterator
* with the results of fn(item)
*
* ## Example
* ```typescript
* [...map(e => e*e, [1, 2, 3])] // [1, 4, 9]
* ```
*/
export declare const map: {
<T, U>(fn: (item: T) => Awaitable<U>, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<U>;
<T, U>(fn: (item: T) => Awaitable<U>): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<U>;
};
/**
* Like map but filter out undefined results
*
* ## Example
* ```typescript
* [...flatMap(e => e % 2 === 0 ? undefined : e*e, [1, 2, 3])] // [1, 9]
* ```
*
* ## Why not map(filter())?
* filterMap is functionally equivalent to map(filter()) but can give
* cleaner code and higher performance for cases where filtering is applied
* to the mapped value and not the input value.
*/
export declare const filterMap: {
<T, U>(fn: (item: T) => Awaitable<U | undefined>, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<U>;
<T, U>(fn: (item: T) => Awaitable<U | undefined>): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<U>;
};
/**
* Like map but flattens the result a single level
*
* ## Example
* ```typescript
* [...flatMap(e => [e, e*e], [1, 2, 3])] // [1, 1, 2, 4, 3, 9]
* ```
*/
export declare const flatMap: {
<T, U>(fn: (item: T) => AsyncIterableOrIterator<U>, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<U>;
<T, U>(fn: (item: T) => AsyncIterableOrIterator<U>): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<U>;
};
/**
* Flattens an iterator a single level
*
* ## Example
* ```typescript
* [...flatten([[1, 2], [], [3]])] // [1, 2, 3]
* ```
*/
export declare const flatten: {
<T>(asyncIterator: AsyncIterableOrIterator<AsyncIterableOrIterator<T>>): AsyncIterableIterator<T>;
};
/**
* Calls predicate for every item in the iterator to produce an iterator
* with only the items for which predicate returns true
*
* ## Example
* ```typescript
* [...filter(e => e > 2, [1, 2, 3])] // [2, 3]
* ```
*/
export declare const filter: {
<T>(fn: (item: T) => boolean, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<T>;
<T>(fn: (item: T) => boolean): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<T>;
};
/**
* Reduces an iterator to a single value by iteratively combining each
* item of the iterator with an existing value
*
* Uses initialValue as the initial value, then iterates through the elements
* and updates the value with each element using the combine function.
*
* If the iterator is empty, the initialValue is returned.
*
* ## Example
* ```typescript
* fold(0, (sum, item) => sum + item, [1, 2, 3]) // 6
* ```
*/
export declare const fold: {
<T, U>(initialValue: U, combine: (previousItem: U, item: T) => Awaitable<U>, asyncIterator: AsyncIterableOrIterator<T>): Promise<U>;
<T, U>(initialValue: U, combine: (previousItem: U, item: T) => U): (asyncIterator: AsyncIterableOrIterator<T>) => Promise<U>;
};
/**
* Like fold, scan iteratively combines each item of the iterator with
* an existing value. Scan does however yield each intermediate value.
*
* If the iterator is empty, no value is yielded.
*
* ## Example
* ```typescript
* scan(0, (sum, item) => sum + item, [1, 2, 3]) // [1, 3, 6]
* ```
*/
export declare const scan: {
<T, U>(initialValue: U, combine: (previousItem: U, item: T) => Awaitable<U>, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<U>;
<T, U>(initialValue: U, combine: (previousItem: U, item: T) => U): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<U>;
};
/**
* Transforms an iterator into a Map.
*
* Calls `fn` for every item in the iterator. `fn` should return a tuple of `[key, value]`
* for that item.
*
* If multiple items returns the same key the latter will overwrite the former.
* This behavior can be changed by passing `merge` in the options object.
*
* `merge` takes the current value, the new value and the key and should return a combined
* value. It can also throw to dissallow multiple items returning the same key.
*
* ## Example
* ```typescript
* collect(e => [e, e*e], [1, 2, 3]) // Map {1 => 1, 2 => 4, 3 => 9}
* ```
*
* ### Using merge
* ```typescript
* collect(
* e => [e % 2 === 0 ? 'even' : 'odd', [e]],
* [1, 2, 3],
* {merge: (a, b) => a.concat(b)}
* )
* // Map {'odd' => [1, 3], 'even' => [2]}
* ```
*/
export declare const collect: {
<T, U, K = string>(fn: (item: T) => Awaitable<[K, U]>, iterator: AsyncIterableOrIterator<T>, options?: {
merge?: (currentValue: U, newValue: U, key: K) => U;
}): Promise<Map<K, U>>;
<T, U, K = string>(fn: (item: T) => Awaitable<[K, U]>, options: {
merge?: (currentValue: U, newValue: U, key: K) => U;
}): (iterator: AsyncIterableOrIterator<T>) => Promise<Map<K, U>>;
<T, U, K = string>(fn: (item: T) => Awaitable<[K, U]>): (iterator: AsyncIterableOrIterator<T>, options?: {
merge?: (currentValue: U, newValue: U, key: K) => U;
}) => Promise<Map<K, U>>;
};
/**
* Transforms an iterator into an Object.
*
* Calls `fn` for every item in the iterator. `fn` should return a tuple of `[key, value]`
* for that item.
*
* If multiple items returns the same key the latter will overwrite the former.
* This behavior can be changed by passing `merge` in the options object.
*
* `merge` takes the current value, the new value and the key and should return a combined
* value. It can also throw to dissallow multiple items returning the same key.
*
* ## Example
* ```typescript
* collectRecord(e => [e, e*e], [1, 2, 3]) // {1: 1, 2: 4, 3: 9}
* ```
*
* ### Using merge
* ```typescript
* collectRecord(
* e => [e % 2 === 0 ? 'even' : 'odd', [e]],
* [1, 2, 3],
* {merge: (a, b) => a.concat(b)}
* )
* // {odd: [1, 3], even: [2]}
* ```
*/
export declare const collectRecord: {
<T, U, K extends string>(fn: (item: T) => Awaitable<[K, U]>, iterator: AsyncIterableOrIterator<T>, options?: {
merge?: (currentValue: U, newValue: U, key: K) => U;
}): Promise<Record<K, U>>;
<T, U, K extends string>(fn: (item: T) => Awaitable<[K, U]>, options: {
merge?: (currentValue: U, newValue: U, key: K) => U;
}): (iterator: AsyncIterableOrIterator<T>) => Promise<Record<K, U>>;
<T, U, K extends string>(fn: (item: T) => Awaitable<[K, U]>): (iterator: AsyncIterableOrIterator<T>, options?: {
merge?: (currentValue: U, newValue: U, key: K) => U;
}) => Promise<Record<K, U>>;
};
/**
* Zips two iterators by taking the next value of each iterator as a tuple
*
* If the two iterators have a different length, it will zip until the first iterator ends
* and then end with a return value of the longer iterator.
*
* ## Example
* ```typescript
* [...zip([1, 2, 3], ['a', 'b', 'c']) // [[1, 'a'], [2, 'b'], [3, 'c']]
* ```
*/
export declare const zip: {
<A, B>(a: AsyncIterableOrIterator<A>, b: AsyncIterableOrIterator<B>): AsyncIterableIterator<[A, B]>;
<A, B>(a: AsyncIterableOrIterator<A>): (b: AsyncIterableOrIterator<B>) => AsyncIterableIterator<[A, B]>;
};
/**
* Creates an iterator that only yields the first item yielded by the source
* iterator during a window lasting the specified duration
*
* ## Example
* ```typescript
* const timestamps = new Subject<Date>()
* const throttledTimestamps = throttle(2000, timestamps)
*
* setInterval(() => timestamps.next(new Date()), 1000)
*
* for await (const timestamp of throttledTimestamps) {
* console.log(timestamp); // Will log the current time every other second
* }
* ```
*/
export declare const throttle: {
<T>(duration: number, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<T>;
<T>(duration: number): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<T>;
};
/**
* Returns true if predicate returns true for every item in the iterator
*
* Returns true if the iterator is empty
*
* ## Example
* ```typescript
* await all(e => e > 1, [1, 2, 3]) // false
* await all(e => e > 0, [1, 2, 3]) // true
* await all(e => e > 1, []) // true
* ```
*/
export declare const all: {
<T>(predicate: (item: T) => Awaitable<boolean>, asyncIterator: AsyncIterableOrIterator<T>): Promise<boolean>;
<T>(predicate: (item: T) => Awaitable<boolean>): (asyncIterator: AsyncIterableOrIterator<T>) => Promise<boolean>;
};
/**
* Returns true if predicate returns true for any item in the iterator
*
* Returns false if the iterator is empty
*
* ## Example
* ```typescript
* await any(e => e > 1, [1, 2, 3]) // true
* await any(e => e > 3, [1, 2, 3]) // false
* await any(e => e > 1, []) // false
* ```
*/
export declare const any: {
<T>(predicate: (item: T) => Awaitable<boolean>, asyncIterator: AsyncIterableOrIterator<T>): Promise<boolean>;
<T>(predicate: (item: T) => Awaitable<boolean>): (asyncIterator: AsyncIterableOrIterator<T>) => Promise<boolean>;
};
/**
* Calls fn for every item and returns the first item for which fn returns true
*
* Returns undefined if fn return fals for all items or if the iterator is empty
*
* ## Example
* ```typescript
* await find(e => e > 1, [1, 2, 3]) // 2
* ```
*/
export declare const find: {
<T>(fn: (item: T) => Awaitable<boolean>, asyncIterator: AsyncIterableOrIterator<T>): Promise<T | undefined>;
<T>(fn: (item: T) => Awaitable<boolean>): (asyncIterator: AsyncIterableOrIterator<T>) => Promise<T | undefined>;
};
/**
* Consumes an iterator, creating two Arrays from it
*
* The predicate passed to partition() can return true, or false.
* partition() returns a pair, all of the elements for which it returned
* true, and all of the elements for which it returned false.
*
* ## Example
* ```typescript
* const [even, odd] = await partition(e => e % 2 === 0, [1, 2, 3])
*
* expect(even).toEqual([2])
* expect(odd).toEqual([1, 3])
* ```
*/
export declare const partition: {
<T>(fn: (item: T) => boolean, iterator: AsyncIterableOrIterator<T>): Promise<[
Array<T>,
Array<T>
]>;
<T>(fn: (item: T) => boolean): (iterator: AsyncIterableOrIterator<T>) => Promise<[Array<T>, Array<T>]>;
};
/**
* Returns the first value of the iterator or undefined if it's empty
*
* ## Example
* ```typescript
* await first([1, 2, 3]) // 1
* ```
*/
export declare function first<T>(asyncIterator: AsyncIterableOrIterator<T>): Promise<T | undefined>;
/**
* Returns an iterator with the first count values of the iterator
*
* The returned iterator may hold fewer than `count` values if the
* iterator contains less items than `count`
*
* ## Example
* ```typescript
* await take(2, [1, 2, 3]) // [1, 2]
* ```
*/
export declare const take: {
<T>(count: number, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<T>;
<T>(count: number): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<T>;
};
/**
* Yields values until the notifier iterable yields a value
*/
export declare const takeUntil: {
<T>(notifier: AsyncIterableOrIterator<any>, asyncIterator: AsyncIterableOrIterator<T>): AsyncIterableIterator<T>;
<T>(notifier: AsyncIterableOrIterator<any>): (asyncIterator: AsyncIterableOrIterator<T>) => AsyncIterableIterator<T>;
};
/**
* Returns the last value of the iterator or undefined if it's empty
*
* ## Example
* ```typescript
* await last([1, 2, 3]) // 3
* ```
*/
export declare function last<T>(asyncIterator: AsyncIterableOrIterator<T>): Promise<T | undefined>;
//# sourceMappingURL=async.d.ts.map