Options
All
• Public
• Public/Protected
• All

# Project @shlappas/itertools

## 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
``````

#### 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
``````

#### Parameters

• ##### reducer: (accumulated: R | undefined, nextVal: T) => R
• (accumulated: R | undefined, nextVal: T): 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
``````

#### Parameters

• ##### reducer: (accumulated: R, nextItem: T) => R
• (accumulated: R, nextItem: T): 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()                          // 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
``````

#### Parameters

• ##### predicate: (value: T) => boolean = ...
• (value: T): 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()                          // 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
``````

#### Parameters

• ##### predicate: (value: T) => boolean = ...
• (value: T): boolean

### chain

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

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

### 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

### 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.

### 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
``````

### 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(, 42) // => false
contains(, 3) // => true
contains([{}, {}], {}) // => false, since comparison is done with ===
``````

### 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

[...count(5, 3)] // Infinite loop!
``````

### 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
``````

### 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.

#### Parameters

• ##### predicate: (value: T) => boolean = ...
• (value: T): boolean

### 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]]
``````

### 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']
``````

#### Parameters

• ##### predicate: (value: T) => boolean = ...
• (value: T): boolean

### 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]]
``````

#### 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]  [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], , [4, 5]]
``````

#### Parameters

• ##### keyFunc: (item: T) => K

A function computing a key value for each element.

• (item: T): K

### 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.

#### 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.

### 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]
``````

#### Parameters

• ##### mapper: (...values: T) => M
• (...values: T): 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.

### product

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

### range

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

#### 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]
``````

### 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
``````

#### Parameters

• ##### reducer: (accumulated: R, nextVal: T) => R
• (accumulated: R, nextVal: T): 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
``````

#### Parameters

• ##### reducer: (accumulated: T, nextVal: T) => T
• (accumulated: T, nextVal: T): T

### 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]
``````

#### Parameters

• ##### value: T

The value to yield

• ##### times: number = ...

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

### 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.

#### Parameters

• ##### predicate: (value: T) => boolean = ...
• (value: T): boolean

### 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]]
``````

### 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', )] // [['H', 3], ['a', undefined], ['t', undefined]]
``````

#### Returns Generator<Partial<T>>

Generated using TypeDoc