UNPKG

itertools

Version:

A JavaScript port of Python's awesome itertools standard library

484 lines (478 loc) 20.5 kB
type Predicate<T> = (value: T, index: number) => boolean; type Primitive = string | number | boolean; /** * Returns the first item in the iterable for which the predicate holds, if * any. If no predicate is given, it will return the first value returned by * the iterable. */ declare function find<T>(iterable: Iterable<T>, predicate?: Predicate<T>): T | undefined; /** * Returns true when all of the items in iterable are truthy. An optional key * function can be used to define what truthiness means for this specific * collection. * * Examples: * * all([]) // => true * all([0]) // => false * all([0, 1, 2]) // => false * all([1, 2, 3]) // => true * * Examples with using a key function: * * all([2, 4, 6], n => n % 2 === 0) // => true * all([2, 4, 5], n => n % 2 === 0) // => false * */ declare function every<T>(iterable: Iterable<T>, predicate?: Predicate<T>): boolean; /** * Returns true when some of the items in iterable are truthy. An optional key * function can be used to define what truthiness means for this specific * collection. * * Examples: * * some([]) // => false * some([0]) // => false * some([0, 1, null, undefined]) // => true * * Examples with using a key function: * * some([1, 4, 5], n => n % 2 === 0) // => true * some([{name: 'Bob'}, {name: 'Alice'}], person => person.name.startsWith('C')) // => false * */ declare function some<T>(iterable: Iterable<T>, predicate?: Predicate<T>): boolean; /** * Alias of `every()`. */ declare const all: typeof every; /** * Alias of `some()`. */ declare const any: typeof some; /** * Returns true when any of the items in the iterable are equal to the target object. * * Examples: * * contains([], 'whatever') // => false * contains([3], 42) // => false * contains([3], 3) // => true * contains([0, 1, 2], 2) // => true * */ declare function contains<T>(haystack: Iterable<T>, needle: T): boolean; /** * Returns an iterable of enumeration pairs. Iterable must be a sequence, an * iterator, or some other object which supports iteration. The elements * produced by returns a tuple containing a counter value (starting from 0 by * default) and the values obtained from iterating over given iterable. * * Example: * * import { enumerate } from 'itertools'; * * console.log([...enumerate(['hello', 'world'])]); * // [0, 'hello'], [1, 'world']] */ declare function enumerate<T>(iterable: Iterable<T>, start?: number): IterableIterator<[number, T]>; /** * Non-lazy version of ifilter(). */ declare function filter<T, N extends T>(iterable: Iterable<T>, predicate: (item: T, index: number) => item is N): N[]; declare function filter<T>(iterable: Iterable<T>, predicate: Predicate<T>): T[]; /** * Returns an iterator object for the given iterable. This can be used to * manually get an iterator for any iterable datastructure. The purpose and * main use case of this function is to get a single iterator (a thing with * state, think of it as a "cursor") which can only be consumed once. */ declare function iter<T>(iterable: Iterable<T>): IterableIterator<T>; /** * Non-lazy version of imap(). */ declare function map<T, V>(iterable: Iterable<T>, mapper: (item: T) => V): V[]; /** * Return the largest item in an iterable. Only works for numbers, as ordering * is pretty poorly defined on any other data type in JS. The optional `keyFn` * argument specifies a one-argument ordering function like that used for * sorted(). * * If the iterable is empty, `undefined` is returned. * * If multiple items are maximal, the function returns either one of them, but * which one is not defined. */ declare function max<T>(iterable: Iterable<T>, keyFn?: (item: T) => number): T | undefined; /** * Return the smallest item in an iterable. Only works for numbers, as * ordering is pretty poorly defined on any other data type in JS. The * optional `keyFn` argument specifies a one-argument ordering function like * that used for sorted(). * * If the iterable is empty, `undefined` is returned. * * If multiple items are minimal, the function returns either one of them, but * which one is not defined. */ declare function min<T>(iterable: Iterable<T>, keyFn?: (item: T) => number): T | undefined; /** * Returns an iterator producing all the numbers in the given range one by one, * starting from `start` (default 0), as long as `i < stop`, in increments of * `step` (default 1). * * `range(a)` is a convenient shorthand for `range(0, a)`. * * Various valid invocations: * * range(5) // [0, 1, 2, 3, 4] * range(2, 5) // [2, 3, 4] * range(0, 5, 2) // [0, 2, 4] * range(5, 0, -1) // [5, 4, 3, 2, 1] * range(-3) // [] * * For a positive `step`, the iterator will keep producing values `n` as long * as the stop condition `n < stop` is satisfied. * * For a negative `step`, the iterator will keep producing values `n` as long * as the stop condition `n > stop` is satisfied. * * The produced range will be empty if the first value to produce already does * not meet the value constraint. */ declare function range(stop: number): IterableIterator<number>; declare function range(start: number, stop: number, step?: number): IterableIterator<number>; /** * Apply function of two arguments cumulatively to the items of sequence, from * left to right, so as to reduce the sequence to a single value. For example: * * reduce([1, 2, 3, 4, 5], (x, y) => x + y, 0) * * calculates * * (((((0+1)+2)+3)+4)+5) * * The left argument, `x`, is the accumulated value and the right argument, * `y`, is the update value from the sequence. * * **Difference between `reduce()` and `reduce\_()`**: `reduce()` requires an * explicit initializer, whereas `reduce_()` will automatically use the first * item in the given iterable as the initializer. When using `reduce()`, the * initializer value is placed before the items of the sequence in the * calculation, and serves as a default when the sequence is empty. When using * `reduce_()`, and the given iterable is empty, then no default value can be * derived and `undefined` will be returned. */ declare function reduce<T>(iterable: Iterable<T>, reducer: (agg: T, item: T, index: number) => T): T | undefined; declare function reduce<T, O>(iterable: Iterable<T>, reducer: (agg: O, item: T, index: number) => O, start: O): O; /** * Return a new sorted list from the items in iterable. * * Has two optional arguments: * * * `keyFn` specifies a function of one argument providing a primitive * identity for each element in the iterable. that will be used to compare. * The default value is to use a default identity function that is only * defined for primitive types. * * * `reverse` is a boolean value. If `true`, then the list elements are * sorted as if each comparison were reversed. */ declare function sorted<T>(iterable: Iterable<T>, keyFn?: (item: T) => Primitive, reverse?: boolean): T[]; /** * Sums the items of an iterable from left to right and returns the total. The * sum will defaults to 0 if the iterable is empty. */ declare function sum(iterable: Iterable<number>): number; /** * See izip. */ declare function zip<T1, T2>(xs: Iterable<T1>, ys: Iterable<T2>): [T1, T2][]; /** * See izip3. */ declare function zip3<T1, T2, T3>(xs: Iterable<T1>, ys: Iterable<T2>, zs: Iterable<T3>): [T1, T2, T3][]; /** * Returns an iterable, filtering out any "nullish" values from the iterable. * * >>> compact([1, 2, undefined, 3, null]) * [1, 2, 3] * * For an eager version, @see compact(). */ declare function icompact<T>(iterable: Iterable<T | null | undefined>): IterableIterator<T>; /** * Returns an array, filtering out any "nullish" values from the iterable. * * >>> compact([1, 2, undefined, 3, null]) * [1, 2, 3] * * For a lazy version, @see icompact(). */ declare function compact<T>(iterable: Iterable<T | null | undefined>): T[]; /** * Removes all "nullish" values from the given object. Returns a new object. * * >>> compactObject({ a: 1, b: undefined, c: 0, d: null }) * { a: 1, c: 0 } * */ declare function compactObject<K extends string, V>(obj: Record<K, V | null | undefined>): Record<K, V>; /** * Almost an alias of find(). There only is a difference if no key fn is * provided. In that case, `find()` will return the first item in the iterable, * whereas `first()` will return the first non-`undefined` value in the * iterable. */ declare function first<T>(iterable: Iterable<T>, keyFn?: Predicate<T>): T | undefined; /** * Returns 0 or more values for every value in the given iterable. * Technically, it's just calling map(), followed by flatten(), but it's a very * useful operation if you want to map over a structure, but not have a 1:1 * input-output mapping. Instead, if you want to potentially return 0 or more * values per input element, use flatmap(): * * For example, to return all numbers `n` in the input iterable `n` times: * * >>> const repeatN = n => repeat(n, n); * >>> [...flatmap([0, 1, 2, 3, 4], repeatN)] * [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] // note: no 0 * */ declare function flatmap<T, S>(iterable: Iterable<T>, mapper: (item: T) => Iterable<S>): IterableIterator<S>; /** * Returns an iterator that returns elements from the first iterable until it * is exhausted, then proceeds to the next iterable, until all of the iterables * are exhausted. Used for treating consecutive sequences as a single * sequence. */ declare function chain<T>(...iterables: Iterable<T>[]): IterableIterator<T>; /** * Returns an iterator that counts up values starting with number `start` * (default 0), incrementing by `step`. To decrement, use a negative step * number. */ declare function count(start?: number, step?: number): IterableIterator<number>; /** * Non-lazy version of icompress(). */ declare function compress<T>(data: Iterable<T>, selectors: Iterable<boolean>): T[]; /** * Returns an iterator producing elements from the iterable and saving a copy * of each. When the iterable is exhausted, return elements from the saved * copy. Repeats indefinitely. */ declare function cycle<T>(iterable: Iterable<T>): IterableIterator<T>; /** * Returns an iterator that drops elements from the iterable as long as the * predicate is true; afterwards, returns every remaining element. Note, the * iterator does not produce any output until the predicate first becomes * false. */ declare function dropwhile<T>(iterable: Iterable<T>, predicate: Predicate<T>): IterableIterator<T>; declare function groupby<T, K extends Primitive>(iterable: Iterable<T>, keyFn?: (item: T) => K): Generator<[K, Generator<T, undefined>], undefined>; /** * Returns an iterator that filters elements from data returning only those * that have a corresponding element in selectors that evaluates to `true`. * Stops when either the data or selectors iterables has been exhausted. */ declare function icompress<T>(data: Iterable<T>, selectors: Iterable<boolean>): IterableIterator<T>; /** * Returns an iterator that filters elements from iterable returning only those * for which the predicate is true. */ declare function ifilter<T, N extends T>(iterable: Iterable<T>, predicate: (item: T) => item is N): IterableIterator<N>; declare function ifilter<T>(iterable: Iterable<T>, predicate: Predicate<T>): IterableIterator<T>; /** * Returns an iterator that computes the given mapper function using arguments * from each of the iterables. */ declare function imap<T, V>(iterable: Iterable<T>, mapper: (item: T) => V): IterableIterator<V>; /** * Returns an iterator that returns selected elements from the iterable. If * `start` is non-zero, then elements from the iterable are skipped until start * is reached. Then, elements are returned by making steps of `step` (defaults * to 1). If set to higher than 1, items will be skipped. If `stop` is * provided, then iteration continues until the iterator reached that index, * otherwise, the iterable will be fully exhausted. `islice()` does not * support negative values for `start`, `stop`, or `step`. */ declare function islice<T>(iterable: Iterable<T>, stop: number): IterableIterator<T>; declare function islice<T>(iterable: Iterable<T>, start: number, stop?: number | null, step?: number): IterableIterator<T>; /** * Returns an iterator that aggregates elements from each of the iterables. * Used for lock-step iteration over several iterables at a time. When * iterating over two iterables, use `izip2`. When iterating over three * iterables, use `izip3`, etc. `izip` is an alias for `izip2`. */ declare function izip<T1, T2>(xs: Iterable<T1>, ys: Iterable<T2>): IterableIterator<[T1, T2]>; /** * Like izip2, but for three input iterables. */ declare function izip3<T1, T2, T3>(xs: Iterable<T1>, ys: Iterable<T2>, zs: Iterable<T3>): IterableIterator<[T1, T2, T3]>; declare const izip2: typeof izip; /** * Returns an iterator that aggregates elements from each of the iterables. If * the iterables are of uneven length, missing values are filled-in with * fillvalue. Iteration continues until the longest iterable is exhausted. */ declare function izipLongest2<T1, T2, D>(xs: Iterable<T1>, ys: Iterable<T2>, filler?: D): IterableIterator<[T1 | D, T2 | D]>; /** * See izipLongest2, but for three. */ declare function izipLongest3<T1, T2, T3, D = undefined>(xs: Iterable<T1>, ys: Iterable<T2>, zs: Iterable<T3>, filler?: D): IterableIterator<[T1 | D, T2 | D, T3 | D]>; /** * Like the other izips (`izip`, `izip3`, etc), but generalized to take an * unlimited amount of input iterables. Think `izip(*iterables)` in Python. * * **Note:** Due to Flow type system limitations, you can only "generially" zip * iterables with homogeneous types, so you cannot mix types like <A, B> like * you can with izip2(). */ declare function izipMany<T>(...iters: Iterable<T>[]): IterableIterator<T[]>; /** * Return successive `r`-length permutations of elements in the iterable. * * If `r` is not specified, then `r` defaults to the length of the iterable and * all possible full-length permutations are generated. * * Permutations are emitted in lexicographic sort order. So, if the input * iterable is sorted, the permutation tuples will be produced in sorted order. * * Elements are treated as unique based on their position, not on their value. * So if the input elements are unique, there will be no repeat values in each * permutation. */ declare function permutations<T>(iterable: Iterable<T>, r?: number): IterableIterator<T[]>; /** * Returns an iterator that produces values over and over again. Runs * indefinitely unless the times argument is specified. */ declare function repeat<T>(thing: T, times?: number): IterableIterator<T>; /** * Returns an iterator that produces elements from the iterable as long as the * predicate is true. */ declare function takewhile<T>(iterable: Iterable<T>, predicate: Predicate<T>): IterableIterator<T>; declare function zipLongest2<T1, T2, D>(xs: Iterable<T1>, ys: Iterable<T2>, filler?: D): [T1 | D, T2 | D][]; declare function zipLongest3<T1, T2, T3, D>(xs: Iterable<T1>, ys: Iterable<T2>, zs: Iterable<T3>, filler?: D): [T1 | D, T2 | D, T3 | D][]; declare const izipLongest: typeof izipLongest2; declare const zipLongest: typeof zipLongest2; declare function zipMany<T>(...iters: Iterable<T>[]): T[][]; /** * Break iterable into lists of length `size`: * * [...chunked([1, 2, 3, 4, 5, 6], 3)] * // [[1, 2, 3], [4, 5, 6]] * * If the length of iterable is not evenly divisible by `size`, the last returned * list will be shorter: * * [...chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)] * // [[1, 2, 3], [4, 5, 6], [7, 8]] */ declare function chunked<T>(iterable: Iterable<T>, size: number): IterableIterator<T[]>; /** * Return an iterator flattening one level of nesting in a list of lists: * * [...flatten([[0, 1], [2, 3]])] * // [0, 1, 2, 3] * */ declare function flatten<T>(iterableOfIterables: Iterable<Iterable<T>>): IterableIterator<T>; /** * Intersperse filler element `value` among the items in `iterable`. * * >>> [...intersperse(-1, range(1, 5))] * [1, -1, 2, -1, 3, -1, 4] * */ declare function intersperse<T, V>(value: V, iterable: Iterable<T>): IterableIterator<T | V>; /** * Returns an iterable containing only the first `n` elements of the given * iterable. */ declare function itake<T>(n: number, iterable: Iterable<T>): IterableIterator<T>; /** * Returns an iterator of paired items, overlapping, from the original. When * the input iterable has a finite number of items `n`, the outputted iterable * will have `n - 1` items. * * >>> pairwise([8, 2, 0, 7]) * [(8, 2), (2, 0), (0, 7)] * */ declare function pairwise<T>(iterable: Iterable<T>): IterableIterator<[T, T]>; /** * Returns a 2-tuple of arrays. Splits the elements in the input iterable into * either of the two arrays. Will fully exhaust the input iterable. The first * array contains all items that match the predicate, the second the rest: * * >>> const isOdd = x => x % 2 !== 0; * >>> const iterable = range(10); * >>> const [odds, evens] = partition(iterable, isOdd); * >>> odds * [1, 3, 5, 7, 9] * >>> evens * [0, 2, 4, 6, 8] * */ declare function partition<T, N extends T>(iterable: Iterable<T>, predicate: (item: T, index: number) => item is N): [N[], Exclude<T, N>[]]; declare function partition<T>(iterable: Iterable<T>, predicate: Predicate<T>): [T[], T[]]; /** * Yields the next item from each iterable in turn, alternating between them. * Continues until all items are exhausted. * * >>> [...roundrobin([1, 2, 3], [4], [5, 6, 7, 8])] * [1, 4, 5, 2, 6, 3, 7, 8] */ declare function roundrobin<T>(...iters: Iterable<T>[]): IterableIterator<T>; /** * Yields the heads of all of the given iterables. This is almost like * `roundrobin()`, except that the yielded outputs are grouped in to the * "rounds": * * >>> [...heads([1, 2, 3], [4], [5, 6, 7, 8])] * [[1, 4, 5], [2, 6], [3, 7], [8]] * * This is also different from `zipLongest()`, since the number of items in * each round can decrease over time, rather than being filled with a filler. */ declare function heads<T>(...iters: Iterable<T>[]): IterableIterator<T[]>; /** * Non-lazy version of itake(). */ declare function take<T>(n: number, iterable: Iterable<T>): T[]; /** * Yield unique elements, preserving order. * * >>> [...uniqueEverseen('AAAABBBCCDAABBB')] * ['A', 'B', 'C', 'D'] * >>> [...uniqueEverseen('AbBCcAB', s => s.toLowerCase())] * ['A', 'b', 'C'] * */ declare function uniqueEverseen<T>(iterable: Iterable<T>, keyFn?: (item: T) => Primitive): IterableIterator<T>; /** * Yield only elements from the input that occur more than once. Needs to * consume the entire input before being able to produce the first result. * * >>> [...dupes('AAAABCDEEEFABG')] * [['A', 'A', 'A', 'A', 'A'], ['E', 'E', 'E'], ['B', 'B']] * >>> [...dupes('AbBCcAB', s => s.toLowerCase())] * [['b', 'B', 'B'], ['C', 'c'], ['A', 'A']] * */ declare function dupes<T>(iterable: Iterable<T>, keyFn?: (item: T) => Primitive): IterableIterator<T[]>; /** * Yields elements in order, ignoring serial duplicates. * * >>> [...uniqueJustseen('AAAABBBCCDAABBB')] * ['A', 'B', 'C', 'D', 'A', 'B'] * >>> [...uniqueJustseen('AbBCcAB', s => s.toLowerCase())] * ['A', 'b', 'C', 'A', 'B'] * */ declare function uniqueJustseen<T>(iterable: Iterable<T>, keyFn?: (item: T) => Primitive): IterableIterator<T>; export { type Predicate, type Primitive, all, any, chain, chunked, compact, compactObject, compress, contains, count, cycle, dropwhile, dupes, enumerate, every, filter, find, first, flatmap, flatten, groupby, heads, icompact, icompress, ifilter, imap, intersperse, islice, itake, iter, izip, izip2, izip3, izipLongest, izipLongest3, izipMany, map, max, min, pairwise, partition, permutations, range, reduce, repeat, roundrobin, some, sorted, sum, take, takewhile, uniqueEverseen, uniqueJustseen, zip, zip3, zipLongest, zipLongest3, zipMany };