UNPKG

itertools-ts

Version:

Extended itertools port for TypeScript and JavaScript. Provides a huge set of functions for working with iterable collections (including async ones)

652 lines (651 loc) 21.7 kB
import { AsyncFlatMapper, Comparable, Comparator, Pair, ZipTuple } from "./types"; /** * Provides fluent interface for working with async iterables. */ export declare class AsyncStream<T> implements AsyncIterable<T> { /** * Iterable source */ protected data: AsyncIterable<T>; /** * Creates iterable instance with fluent interface. * * @param data */ static of<T>(data: AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>): AsyncStream<T>; /** * Creates iterable instance with fluent interface from empty iterable source. */ static ofEmpty(): AsyncStream<never>; /** * Creates iterable instance with fluent interface from infinite count iterable. * * @param start (optional, default 1) * @param step (optional, default 1) */ static ofCount(start?: number, step?: number): AsyncStream<number>; /** * Creates iterable instance with fluent interface from infinite collection items repeating. * * @param iterable */ static ofCycle<T>(iterable: AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>): AsyncStream<T>; /** * Creates iterable instance with fluent interface from infinite item repeating. * * @param item */ static ofRepeat<T>(item: T): AsyncStream<T>; /** * Iterate stream collection with another iterable collections simultaneously. * * Make an iterator that aggregates items from multiple iterators. * Similar to Python's zip function. * * For uneven lengths, iterations stops when the shortest iterable is exhausted. * * @param iterables * * @see multi.zipAsync */ zipWith<U extends Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>>(...iterables: U): AsyncStream<ZipTuple<[Iterable<T>, ...U], never>>; /** * Iterate stream collection with another iterable collections simultaneously. * * Make an iterator that aggregates items from multiple iterators. * Similar to Python's zip_longest function. * * Iteration continues until the longest iterable is exhausted. * For uneven lengths, the exhausted iterables will produce `filler` value for the remaining iterations. * * @param filler * @param iterables * * @see multi.zipLongestAsync */ zipFilledWith<U extends Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>, F>(filler: F, ...iterables: U): AsyncStream<ZipTuple<[Iterable<T>, ...U], F>>; /** * Iterate stream collection with another iterable collections simultaneously. * * Make an iterator that aggregates items from multiple iterators. * Similar to Python's zip_longest function. * * Iteration continues until the longest iterable is exhausted. * For uneven lengths, the exhausted iterables will produce `undefined` for the remaining iterations. * * @param iterables * * @see multi.zipLongestAsync */ zipLongestWith<U extends Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>>(...iterables: U): AsyncStream<ZipTuple<[Iterable<T>, ...U], undefined>>; /** * Iterate stream collection with another iterable collections of equal lengths simultaneously. * * Works like multi.zip() method but throws LengthException if lengths not equal, * i.e., at least one iterator ends before the others. * * @param iterables * * @see multi.zipEqualAsync */ zipEqualWith<U extends Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>>(...iterables: U): AsyncStream<ZipTuple<[Iterable<T>, ...U], never>>; /** * Chain stream collection withs given iterables together into a single iteration. * * Makes a single continuous sequence out of multiple sequences. * * @param iterables * * @see multi.chainAsync */ chainWith(...iterables: Array<AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>>): AsyncStream<T>; /** * Return overlapped chunks of elements from iterable source. * * Chunk size must be at least 1. * * Overlap size must be less than chunk size. * * @param chunkSize * @param overlapSize * @param includeIncompleteTail * * @see single.chunkwiseOverlapAsync */ chunkwiseOverlap(chunkSize: number, overlapSize: number, includeIncompleteTail?: boolean): AsyncStream<Array<T>>; /** * Return chunks of elements from iterable source. * * Chunk size must be at least 1. * * @param chunkSize * * @see single.chunkwiseAsync */ chunkwise(chunkSize: number): AsyncStream<Array<T>>; /** * Compress an iterable source by filtering out data that is not selected. * * Selectors indicate which data. True value selects item. False value filters out data. * * @param selectors * * @see single.compressAsync */ compress(selectors: AsyncIterable<number | boolean> | AsyncIterator<number | boolean> | Iterable<number | boolean> | Iterator<number | boolean>): AsyncStream<T>; /** * Drop elements from the iterable source while the predicate function is true. * * Once the predicate function returns false once, all remaining elements are returned. * * @param predicate * * @see single.dropWhileAsync */ dropWhile(predicate: (item: T) => Promise<boolean> | boolean): AsyncStream<T>; /** * Filter out elements from the iterable source only returning elements where there predicate function is true. * * @param predicate * * @see single.filterAsync */ filter(predicate: (item: T) => Promise<boolean> | boolean): AsyncStream<T>; /** * Enumerates items of given collection. * * @see single.enumerateAsync */ enumerate(): AsyncStream<[number, T]>; /** * Iterates keys from the collection of key-value pairs. * * @see single.keysAsync */ keys(): AsyncStream<T extends [infer TKey, infer _] ? TKey : never>; /** * Limit iteration to a max size limit. * * @param count * * @see single.limitAsync */ limit(count: number): AsyncStream<T>; /** * Map a function onto every element of the stream * * @param mapper * * @see single.mapAsync */ map<U>(mapper: (datum: T) => Promise<U> | U): AsyncStream<U>; /** * Returns a new collection formed by applying a given callback function * to each element of the stream, and then flattening the result by one level. * * @param mapper * * @see single.flatMapAsync */ flatMap<U>(mapper: AsyncFlatMapper<T, U>): AsyncStream<U>; /** * Flatten a stream. * * @param dimensions * * @see single.flattenAsync */ flatten(dimensions?: number): AsyncStream<unknown>; /** * Group stream data by a common data element. * * Iterate pairs of group name and collection of grouped items. * * Collection of grouped items may be an array or an object (depends on presence of `itemKeyFunction` param). * * The `groupKeyFunction` determines the key (or multiple keys) to group elements by. * * The `itemKeyFunction` (optional) determines the key of element in group. * * @param groupKeyFunction * @param itemKeyFunction * * @see single.groupByAsync */ groupBy<TItemKeyFunction extends ((item: T) => string) | undefined, TResultItem extends TItemKeyFunction extends undefined ? [string, Array<T>] : [string, Record<string, T>]>(groupKeyFunction: (item: T) => Promise<string> | string, itemKeyFunction?: TItemKeyFunction): AsyncStream<TResultItem>; /** * Return pairs of elements from iterable source. * * Produces empty generator if given collection contains less than 2 elements. * * @see single.pairwiseAsync */ pairwise(): AsyncStream<Pair<T>>; /** * Accumulate the running average (mean) over the stream. * * @param initialValue (Optional) If provided, the running average leads off with the initial value. * * @see math.runningAverageAsync */ runningAverage(initialValue?: number): AsyncStream<number>; /** * Accumulate the running difference over the stream. * * @param initialValue (Optional) If provided, the running difference leads off with the initial value. * * @see math.runningDifferenceAsync */ runningDifference(initialValue?: number): AsyncStream<number>; /** * Accumulate the running max over the stream. * * @param initialValue (Optional) If provided, the running max leads off with the initial value. * * @see math.runningMaxAsync */ runningMax(initialValue?: number): AsyncStream<number>; /** * Accumulate the running min over the stream. * * @param initialValue (Optional) If provided, the running min leads off with the initial value. * * @see math.runningMinAsync */ runningMin(initialValue?: number): AsyncStream<number>; /** * Accumulate the running product over the stream. * * @param initialValue (Optional) If provided, the running product leads off with the initial value. * * @see math.runningProductAsync */ runningProduct(initialValue?: number): AsyncStream<number>; /** * Accumulate the running total over the stream. * * @param initialValue (Optional) If provided, the running total leads off with the initial value. * * @see math.runningTotalAsync */ runningTotal(initialValue?: number): AsyncStream<number>; /** * Skip n elements in the stream after optional offset. * * @param count * @param offset * * @see single.skipAsync */ skip(count: number, offset?: number): AsyncStream<T>; /** * Extract a slice of the stream. * * @param start * @param count * @param step * * @see single.sliceAsync */ slice(start?: number, count?: number, step?: number): AsyncStream<T>; /** * Return elements from the iterable source as long as the predicate is true. * * If no predicate is provided, the boolean value of the data is used. * * @param predicate * * @see single.takeWhileAsync */ takeWhile(predicate: (item: T) => Promise<boolean> | boolean): AsyncStream<T>; /** * Iterates values from the collection of key-value pairs. * * @see single.valuesAsync */ values(): AsyncStream<T extends [infer _, infer TValue] ? TValue : never>; /** * Sorts the stream. * * If comparator is `undefined`, then elements of the iterable source must be comparable. * * @see single.sort */ sort(comparator?: Comparator<T>): AsyncStream<T>; /** * Filter out elements from the iterable source only returning unique elements. * * @param compareBy * * @see set.distinctAsync */ distinct(compareBy?: (datum: T) => Comparable): AsyncStream<T>; /** * Iterates the intersection of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param iterables * * @see set.intersectionAsync */ intersectionWith(...iterables: Array<AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>>): AsyncStream<T>; /** * Iterates partial intersection of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param minIntersectionCount * @param iterables * * @see set.partialIntersectionAsync */ partialIntersectionWith(minIntersectionCount: number, ...iterables: Array<AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>>): AsyncStream<T>; /** * Iterates the symmetric difference of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param iterables * * @see set.symmetricDifferenceAsync */ symmetricDifferenceWith(...iterables: Array<AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>>): AsyncStream<T>; /** * Iterates union of iterable source and given iterables. * * Always treats different instances of objects and arrays as unequal. * * @param iterables * * @see set.unionAsync */ unionWith(...iterables: Array<AsyncIterable<T> | AsyncIterator<T> | Iterable<T> | Iterator<T>>): AsyncStream<T>; /** * Iterates cartesian product of iterable source and given iterables. * * @param iterables * * @see combinatorics.cartesianProductAsync */ cartesianProductWith<U extends Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>>(...iterables: U): AsyncStream<ZipTuple<[Iterable<T>, ...U], never>>; /** * Iterates all permutations of iterable source. * * @param length * * @see combinatorics.permutations */ permutations(length: number): AsyncStream<Array<T>>; /** * Iterates all combinations of iterable source. * * @param length * * @see combinatorics.combinations */ combinations(length: number): AsyncStream<Array<T>>; /** * Peek at each element between other Stream operations to do some action without modifying the stream. * * Useful for debugging purposes. * * @param callback */ peek(callback: (datum: unknown) => void): AsyncStream<T>; /** * Peek at the entire stream between other Stream operations to do some action without modifying the stream. * * Useful for debugging purposes. * * @param callback */ peekStream(callback: (datum: AsyncStream<T>) => void): AsyncStream<T>; /** * Reduces iterable source like `array.reduce()` function. * * @param reducer * @param initialValue * * @see reduce.toValueAsync */ toValue<U>(reducer: (carry: U, datum: T) => Promise<U> | U, initialValue?: U): Promise<U>; /** * Reduces iterable source to the mean average of its items. * * Returns `undefined` if iterable source is empty. * * @see reduce.toAverageAsync */ toAverage(): Promise<number | undefined>; /** * Reduces iterable source to its length. * * @see reduce.toCountAsync */ toCount(): Promise<number>; /** * Reduces iterable source to its max value. * * Callable param `compareBy` must return comparable value. * * If `compareBy` is not proposed then items of iterable source must be comparable. * * Returns `undefined` if iterable source is empty. * * @param compareBy * * @see reduce.toMaxAsync */ toMax(compareBy?: (datum: T) => Promise<Comparable> | Comparable): Promise<T | undefined>; /** * Reduces iterable source to its min value. * * Callable param `compareBy` must return comparable value. * * If `compareBy` is not proposed then items of iterable source must be comparable. * * Returns `undefined` if iterable source is empty. * * @param compareBy * * @see reduce.toMinAsync */ toMin(compareBy?: (datum: T) => Promise<Comparable> | Comparable): Promise<T | undefined>; /** * Reduces given collection to array of its upper and lower bounds. * * Callable param `compareBy` must return comparable value. * * If `compareBy` is not proposed then items of given collection must be comparable. * * Returns `[undefined, undefined]` if given collection is empty. * * @param compareBy * * @see reduce.toMinMaxAsync */ toMinMax(compareBy?: (item: T) => Promise<Comparable> | Comparable): Promise<[T?, T?]>; /** * Returns the first element of stream. * * @throws LengthError if stream is empty. * * @see reduce.toFirstAsync */ toFirst(): Promise<T>; /** * Returns the first and last elements of stream. * * @throws LengthError if stream is empty. * * @see reduce.toFirstAndLastAsync */ toFirstAndLast(): Promise<[T, T]>; /** * Returns the first element of stream. * * @throws LengthError if stream is empty. * * @see reduce.toLastAsync */ toLast(): Promise<T>; /** * Reduces iterable source to the sum of its items. * * @see reduce.toSumAsync */ toSum(): Promise<number>; /** * Reduces iterable source to the product of its items. * * Returns `undefined` if iterable source is empty. * * @see reduce.toProductAsync */ toProduct(): Promise<number | undefined>; /** * Reduces given collection to its range. * * Returns 0 if given collection is empty. * * @see reduce.toRangeAsync */ toRange(): Promise<number>; /** * Returns true if all elements of stream match the predicate function. * * For empty stream returns true. * * @param predicate * * @see summary.allMatchAsync */ allMatch(predicate: (item: T) => Promise<boolean> | boolean): Promise<boolean>; /** * Returns true if all elements of stream are unique. * * For empty stream returns true. * * Considers different instances of data containers to be different, even if they have the same content. * * @see summary.allUniqueAsync */ allUnique(): Promise<boolean>; /** * Returns true if any element of stream matches the predicate function. * * For empty stream returns false. * * @param predicate * * @see summary.anyMatchAsync */ anyMatch(predicate: (item: T) => Promise<boolean> | boolean): Promise<boolean>; /** * Returns true if exactly n items in the async iterable are true where the predicate function is true. * * Default predicate if not provided is the boolean value of each data item. * * @param n * @param predicate * * @see summary.exactlyNAsync */ exactlyN(n: number, predicate?: (item: T) => Promise<boolean> | boolean): Promise<boolean>; /** * Returns true if stream is sorted in ascending order; otherwise false. * * Items of stream source must be comparable. * * Also returns true if stream is empty or has only one element. * * @see summary.isSortedAsync */ isSorted(): Promise<boolean>; /** * Returns true if stream is sorted in descending order; otherwise false. * * Items of stream source must be comparable. * * Also returns true if stream is empty or has only one element. * * @see summary.isReversedAsync */ isReversed(): Promise<boolean>; /** * Returns true if no element of stream matches the predicate function. * * For empty stream returns true. * * @param predicate * * @see summary.noneMatchAsync */ noneMatch(predicate: (item: T) => Promise<boolean> | boolean): Promise<boolean>; /** * Returns true if stream collection and all given collections are the same. * * For empty collections list returns true. * * @param collections * * @see summary.sameAsync */ sameWith(...collections: Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>): Promise<boolean>; /** * Returns true if stream collection and all given collections have the same lengths. * * For empty collections list returns true. * * @param collections * * @see summary.sameCountAsync */ sameCountWith(...collections: Array<AsyncIterable<unknown> | AsyncIterator<unknown> | Iterable<unknown> | Iterator<unknown>>): Promise<boolean>; /** * Return several independent async streams from current stream. * * Once a tee() has been created, the original iterable should not be used anywhere else; * otherwise, the iterable could get advanced without the tee objects being informed. * * This tool may require significant auxiliary storage (depending on how much temporary data needs to be stored). * In general, if one iterator uses most or all of the data before another iterator starts, * it is faster to use toArray() instead of tee(). * * @param count * * @see transform.teeAsync */ tee(count: number): Array<AsyncStream<T>>; /** * Converts stream to Array. * * @see transform.toArrayAsync */ toArray(): Promise<Array<T>>; /** * Converts stream to Map. * * Stream collection must contain only key-value pairs as elements. * * @see transform.toMapAsync */ toMap(): Promise<T extends [infer TKey, infer TValue] ? Map<TKey, TValue> : never>; /** * Converts stream to Set. * * @see transform.toSetAsync */ toSet(): Promise<Set<T>>; /** * Aggregated iterator. */ [Symbol.asyncIterator](): AsyncIterator<T>; /** * Stream constructor. * * @param iterable */ protected constructor(iterable: AsyncIterable<T>); }