Options
All
  • Public
  • Public/Protected
  • All
Menu

Project @shlappas/itertools

Index

Functions

accumulate

  • accumulate(iterable: Iterable<number>): Generator<number>
  • accumulate<T, R>(iterable: Iterable<T>, reducer: (accumulated: R | undefined, nextVal: T) => R): Generator<R>
  • accumulate<T, R>(iterable: Iterable<T>, reducer: (accumulated: R, nextItem: T) => R, initial: R): Generator<R>
  • An iterator over the prefix sums of the number iterable.

    example
    accumulate([1, 2, 3, 4]) // 1 3 6 10
    

    Parameters

    • iterable: Iterable<number>

    Returns Generator<number>

  • Similar to reduce_, but provides an iterator to the accumulated values.

    Calls the reducer with an undefined accumulated value on the first value in the iterator to produce the initial value.

    see

    reduce_

    example
    accumulate(['bing', 'bang', 'bong'], (n, s) => (n ?? 0) + s.length) // 4, 8, 12
    

    Type parameters

    • T

    • R

    Parameters

    • iterable: Iterable<T>
    • reducer: (accumulated: R | undefined, nextVal: T) => R
        • (accumulated: R | undefined, nextVal: T): R
        • Parameters

          • accumulated: R | undefined
          • nextVal: T

          Returns R

    Returns Generator<R>

  • Similar to reduce, but provides an iterator over the accumulated values.

    Yields the initial value first.

    see

    reduce

    example
    accumulate(['bing', 'bang', 'bong'], (n, s) => n + s.length, 0) // 0, 4, 8, 12
    

    Type parameters

    • T

    • R

    Parameters

    • iterable: Iterable<T>
    • reducer: (accumulated: R, nextItem: T) => R
        • (accumulated: R, nextItem: T): R
        • Parameters

          • accumulated: R
          • nextItem: T

          Returns R

    • initial: R

    Returns Generator<R>

all

  • all<T>(iterable: Iterable<T>, predicate?: (value: T) => boolean): boolean
  • Returns true when all of the items in iterable are truthy. An optional key function can be used to define what truthiness means for the specific iterator.

    example
    all([])                           // true
    all([0])                          // false
    all([0, 1, 2])                    // false
    all([1, 2, 3])                    // true
    
    all([2, 4, 6], n => n % 2 === 0)  // true
    all([2, 4, 5], n => n % 2 === 0)  // false
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • predicate: (value: T) => boolean = ...
        • (value: T): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns boolean

any

  • any<T>(iterable: Iterable<T>, predicate?: (value: T) => boolean): boolean
  • Returns true when all of the items in iterable are truthy. An optional key function can be used to define what truthiness means for the specific iterator.

    example
    any([])                           // false
    any([0])                          // false
    any([0, 1, 2])                    // true
    any([1, 2, 3])                    // true
    
    any([2, 4, 6], n => n % 2 === 0)  // true
    any([2, 4, 5], n => n % 2 === 0)  // true
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • predicate: (value: T) => boolean = ...
        • (value: T): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns boolean

chain

  • chain<T>(...toChain: Iterable<T>[]): Generator<T>
  • An iterator over multiple iterators in order.

    example
    [...chain("Help", [1, 2, 3])].join('') // "Help123"
    

    Type parameters

    • T

    Parameters

    • Rest ...toChain: Iterable<T>[]

    Returns Generator<T>

chainFromIterable

  • chainFromIterable<T>(toChain: Iterable<Iterable<T>>): Generator<T>
  • Alternate to chain. Gets chained inputs from a single iterable argument that is evaluated lazily.

    see

    chain

    Type parameters

    • T

    Parameters

    • toChain: Iterable<Iterable<T>>

    Returns Generator<T>

combinations

  • combinations<T, N>(iterable: Iterable<T>, r: N): Generator<Tuple<T, N>>
  • Iterates over the r-length subsequences of an iterable.

    The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination 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 combination.

    Type parameters

    • T

    • N: number

    Parameters

    • iterable: Iterable<T>
    • r: N

    Returns Generator<Tuple<T, N>>

combinationsWithReplacement

  • combinationsWithReplacement<T, N>(iterable: Iterable<T>, r: N): Generator<Tuple<T, N>>
  • Iterates over the r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

    The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination 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, the generated combinations will also be unique.

    see

    combinations

    example
    combinationsWithReplacement('ABC', 2) // AA AB BB AC BC CC
    

    Type parameters

    • T

    • N: number

    Parameters

    • iterable: Iterable<T>
    • r: N

    Returns Generator<Tuple<T, N>>

contains

  • contains<T>(haystack: Iterable<T>, needle: T): boolean
  • Returns true when any of the items in the iterable are equal (===) to the target object.

    example
    contains([], 'whatever') // => false
    contains([3], 42) // => false
    contains([3], 3) // => true
    contains([{}, {}], {}) // => false, since comparison is done with ===
    

    Type parameters

    • T

    Parameters

    • haystack: Iterable<T>
    • needle: T

    Returns boolean

count

  • count(start?: number, step?: number): Generator<number>
  • Iterates the infinite sequence of start, start + step, start + 2 * step,...

    Be careful to avoid calculating the entire sequence.

    Defaults to start = 0 and step = 1.

    example
    // good
    const it = count(5, 2)
    it.next() // 5
    it.next() // 7
    it.next() // 9
    
    //bad
    [...count(5, 3)] // Infinite loop!
    

    Parameters

    • start: number = 0
    • step: number = 1

    Returns Generator<number>

cycle

  • cycle<T>(iterable: Iterable<T>): Generator<T>
  • Make an iterator yielding elements from the iterable and saving a copy of each. When the iterable is exhausted, yields elements from the saved copy. Repeats indefinitely.

    example
    const it = cycle([1, 2, 3])
    it.next() // 1
    it.next() // 2
    it.next() // 3
    it.next() // 1
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>

    Returns Generator<T>

dropWhile

  • dropWhile<T>(iterable: Iterable<T>, predicate?: (value: T) => boolean): Generator<T>
  • An iterator that drops elements from the passed iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time.

    Defaults to the truthyness of values for the predicate.

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • predicate: (value: T) => boolean = ...
        • (value: T): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns Generator<T>

enumerate

  • enumerate<T>(iterable: Iterable<T>, start?: number): Generator<[number, T]>
  • Returns a generator of enumeration pairs. Iterable must be an object which supports iteration. Produces tuples of the order of each element and the element itself.

    example
    [...enumerate(['hello', 'world'])] // [[0, 'hello'], [1, 'world']]
    [...enumerate([5,4,3,2,1].splice(2), 1)] // [[1, 3], [2, 2], [3, 1]]
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • start: number = 0

    Returns Generator<[number, T]>

filter

  • filter<T>(iterable: Iterable<T>, predicate?: (value: T) => boolean): Generator<T>
  • Returns a generator that filters elements from a given iterable based on a predicate.

    The predicate defaults to the boolean constructor; falsy values will be filtered.

    example
    [...filter([0, 1, 2, 3, 4], n => n % 2 === 0)] // [0, 2, 4]
    [...filter('Hello World!', c => c.match(/[A-Z]/) !== null)] // ['H', 'W']
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • predicate: (value: T) => boolean = ...
        • (value: T): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns Generator<T>

groupBy

  • groupBy<T>(iterable: Iterable<T>): Generator<[T, Iterable<T>]>
  • groupBy<T, K>(iterable: Iterable<T>, keyFunc: (item: T) => K): Generator<[K, Iterable<T>]>
  • An iterator that returns unique values and groups of that value from the iterable. Generally, the iterable needs to already be sorted.

    The operation is similar to the uniq filter in Unix. It generates a break or new group every time the value changes (which is why it is usually necessary to have sorted the data beforehand). This differs from SQL’s GROUP BY which aggregates elements regardless of their input order.

    The group iterator is not saved as the iterator progresses; please pay attention to the second example.

    example
    const values = [0, 0, 1, 1]
    for (const [k, g] of groupBy(values)) {
       console.log(`key = ${k}`)        // 0      1
       console.log(`group = ${[...g]}`) // [0, 0] [1, 1]
    }
    
    [...groupBy(values)].map(([k, g]) => [...g]) // [[], []]
    
    // We could use the iterator version of map though.
    [...map(([k, g]) => [...g], groupBy(values))] // [[0, 0], [1, 1]]
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>

    Returns Generator<[T, Iterable<T>]>

  • An iterator that returns consecutive keys and groups from the iterable. Generally, the iterable needs to already be sorted on the same key function.

    The operation is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data by the key function beforehand). This differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

    The group iterator is not saved as the iterator progresses; please pay attention to the second example.

    example
    const values = [0, 1, 2, 3, 1, 4, 5]
    const keyFunc = v => Math.floor(v / 2)
    
    for (const [k, g] of groupBy(values, keyFunc)) {
       console.log(`key = ${k}`)
       // 0 1 0 2
       console.log(`group = ${[...g]}`)
       // [0, 1] [2, 3] [1] [4, 5]
    }
    
    // The group iterators have all finished by the time we call `Array.prototype.map()`
    [...groupBy(values, keyFunc)].map(([k, g]) => [...g])
    // [[], [], [], []]
    
    // We could use the iterator version of map though.
    [...map(([k, g]) => [...g], groupBy(values, keyFunc))]
    // [[0, 1], [2, 3], [1], [4, 5]]
    

    Type parameters

    • T

    • K

    Parameters

    • iterable: Iterable<T>
    • keyFunc: (item: T) => K

      A function computing a key value for each element.

        • (item: T): K
        • Parameters

          • item: T

          Returns K

    Returns Generator<[K, Iterable<T>]>

islice

  • islice<T>(iterable: Iterable<T>, k: number): Generator<T>
  • islice<T>(iterable: Iterable<T>, start: number, stop?: number, step?: number): Generator<T>
  • An iterator that yields k elements from the iterable.

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • k: number

    Returns Generator<T>

  • An iterator that yields selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. Unlike regular slicing, islice() does not support negative values for start, stop, or step.

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • start: number
    • Optional stop: number
    • Optional step: number

    Returns Generator<T>

map

  • map<T, M>(mapper: (...values: T) => M, ...iterables: Iterableify<T>): Generator<M>
  • Returns a generator over mapped elements from a given iterable based on a given modifying function.

    example
    [...map(n => 'a'.repeat(n), [0, 1, 2])] // ['', 'a', 'aa']
    [...map(c => c.toUpperCase(), 'Hello World!')].join('') // 'HELLO WORLD!'
    [...map((a, b) => a * b, [1, 2, 3], [4, 5, 6])] // [4, 10, 18]
    

    Type parameters

    • T: unknown[]

    • M

    Parameters

    • mapper: (...values: T) => M
        • (...values: T): M
        • Parameters

          • Rest ...values: T

          Returns M

    • Rest ...iterables: Iterableify<T>

    Returns Generator<M>

permutations

  • permutations<T, N>(iterable: Iterable<T>, r?: N): Generator<Tuple<T, N>>
  • An iterator over the r-length permutations of the iterable.

    If r is undefined, then it defaults to the length of the iterable and all possible full-length permutations are generated.

    The permutation tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination 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.

    Type parameters

    • T

    • N: number = number

    Parameters

    • iterable: Iterable<T>
    • Optional r: N

    Returns Generator<Tuple<T, N>>

product

  • product<T>(...toProduct: Iterableify<T>): Generator<T>
  • An iterator over the cartesian product of the input iterables.

    Type parameters

    • T: unknown[]

    Parameters

    • Rest ...toProduct: Iterableify<T>

    Returns Generator<T>

range

  • range(end: number): Generator<number>
  • range(start: number, end: number, step?: number): Generator<number>
  • Iterates over the values 0 <= i < end.

    Parameters

    • end: number

    Returns Generator<number>

  • Returns an iterator producing all the numbers in the given range one by one, starting from start in increments of step (defaults to 1) until end is reached.

    When the step value is positive, the iterator will keep producing values as long as they are less than the end value.

    When the step value is negative, the iterator will keep producing values as long as they are greater than the end value.

    If the step value is 0, it will throw a TypeError.

    The range will be empty if the first value to produce already does not meet the value constraint.

    example
    [...range(0, 3)] // [0, 1, 2]
    [...range(1, 4)] // [1, 2, 3]
    [...range(4, 0, -1)] // [4, 3, 2, 1]
    

    Parameters

    • start: number
    • end: number
    • Optional step: number

    Returns Generator<number>

reduce

  • reduce<T, R>(iterable: Iterable<T>, reducer: (accumulated: R, nextVal: T) => R, initialValue: R): R
  • Accumulates an iterator into a single value with a reducer function.

    DISCLAIMER: it may be tempting to do the following:

    reduce(stringIterator, (n, s) => n + s, '') // concatenate all strings
    

    to concatenate a list of strings, however since strings are immutable in javascript, it is better to use the Array.prototype.join() function to avoid unnecessary copying of strings.

    example
    reduce(['bing', 'bang', 'bong'], (n, s) => n + s.length, 0) // 12
    

    Type parameters

    • T

    • R

    Parameters

    • iterable: Iterable<T>
    • reducer: (accumulated: R, nextVal: T) => R
        • (accumulated: R, nextVal: T): R
        • Parameters

          • accumulated: R
          • nextVal: T

          Returns R

    • initialValue: R

    Returns R

reduce_

  • reduce_<T>(iterable: Iterable<T>, reducer: (accumulated: T, nextVal: T) => T): T | undefined
  • Same as reduce, but uses the first value from the iterable as the initial value.

    see

    reduce

    example
    reduce_([1,2,3], (a, b) => a + b) // 6
    

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • reducer: (accumulated: T, nextVal: T) => T
        • (accumulated: T, nextVal: T): T
        • Parameters

          • accumulated: T
          • nextVal: T

          Returns T

    Returns T | undefined

repeat

  • repeat<T>(value: T, times?: number): Generator<T>
  • An iterator that returns a target value over and over again. Runs indefinitely unless the times argument is specified.

    Used as argument to map() for invariant parameters to the called function. Also used with zip() to create an invariant part of a tuple record.

    example
    repeat(5, 3) // 5 5 5
    map(Math.pow, [1, 2, 3, 4, 5], repeat(2)) // 1 4 9 16 25
    zip(repeat(1), [1, 2, 3]) // [1, 1] [1, 2] [1, 3]
    

    Type parameters

    • T

    Parameters

    • value: T

      The value to yield

    • times: number = ...

      The number of times to yield the value. Defaults to Infinity.

    Returns Generator<T>

takeWhile

  • takeWhile<T>(iterable: Iterable<T>, predicate?: (value: T) => boolean): Generator<T>
  • Iterates over the values of an iterator while they satisfy a predicate.

    Defaults to the truthiness of values as the predicate.

    Type parameters

    • T

    Parameters

    • iterable: Iterable<T>
    • predicate: (value: T) => boolean = ...
        • (value: T): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns Generator<T>

zip

  • zip<T>(...toZip: Iterableify<T>): Generator<T>
  • Iterates over multiple iterators in parallel. Stops as soon as any of the included iterators stop.

    see

    zipLongest

    example
    [...zip('Hello', [3, 2, 1])] // [['H', 3], ['e', 2], ['l', 1]]
    

    Type parameters

    • T: unknown[]

    Parameters

    • Rest ...toZip: Iterableify<T>

    Returns Generator<T>

zipLongest

  • zipLongest<T>(...toZip: Iterableify<T>): Generator<Partial<T>>
  • Iterates over multiple iterators in parallel. Stops when all included iterators stop. Yields undefined for iterators that stop early.

    see

    zip

    example
    [...zipLongest('Hat', [3])] // [['H', 3], ['a', undefined], ['t', undefined]]
    

    Type parameters

    • T: unknown[]

    Parameters

    • Rest ...toZip: Iterableify<T>

    Returns Generator<Partial<T>>

Generated using TypeDoc