itertools-ts
Version:
Extended itertools port for TypeScript and JavaScript. Provides a huge set of functions for working with iterable collections (including async ones)
915 lines (739 loc) • 113 kB
Markdown
# IterTools for TypeScript and JavaScript
[](https://www.npmjs.com/package/itertools-ts)
[](https://www.npmjs.com/package/itertools-ts)
[](https://coveralls.io/github/Smoren/itertools-ts?branch=master)

[](https://bundlephobia.com/result?p=itertools-ts)
[](https://opensource.org/licenses/MIT)

Inspired by Python — designed for TypeScript.
Features
--------
IterTools makes you an iteration superstar by providing two types of tools:
* Loop iteration tools
* Stream iteration tools
* Pipe iteration tools
**Loop Iteration Tools Example**
```typescript
import { multi } from 'itertools-ts';
for (const [letter, number] of multi.zip(['a', 'b'], [1, 2])) {
console.log(`${letter}${number}`); // a1, b2
}
// Async example
const letters = ['a', 'b'].map((x) => Promise.resolve(x));
const numbers = [1, 2].map((x) => Promise.resolve(x));
for await (const [letter, number] of multi.zipAsync(letters, numbers)) {
console.log(`${letter}${number}`); // a1, b2
}
```
**Stream Iteration Tools Example**
```typescript
import { Stream, AsyncStream } from 'itertools-ts';
const result1 = Stream.of([1, 1, 2, 2, 3, 4, 5])
.distinct() // [1, 2, 3, 4, 5]
.map((x) => x**2) // [1, 4, 9, 16, 25]
.filter((x) => x < 10) // [1, 4, 9]
.toSum(); // 14
// Async example
const result2 = await AsyncStream.of([1, 1, 2, 2, 3, 4, 5].map((x) => Promise.resolve(x)))
.distinct() // [1, 2, 3, 4, 5]
.map((x) => x**2) // [1, 4, 9, 16, 25]
.filter((x) => x < 10) // [1, 4, 9]
.toSum(); // 14
```
[More about Streams](#Stream-and-Async-Stream)
**Pipe Iteration Tools Example**
```typescript
import { createPipe } from 'itertools-ts';
const pipe = createPipe(
set.distinct<number>,
(input) => single.map(input, (x) => x**2),
(input) => single.filter(input, (x) => x < 10),
reduce.toSum,
);
const result1 = pipe([1, 1, 2, 2, 3, 4, 5]); // 14
const result2 = pipe([1, 1, 1, 2, 2, 2]); // 5
// Async example
const asyncPipe = createPipe(
set.distinctAsync<number>,
(input) => single.mapAsync(input, (x) => x**2),
(input) => single.filterAsync(input, (x) => x < 10),
reduce.toSumAsync,
);
const result3 = await asyncPipe([1, 1, 2, 2, 3, 4, 5].map((x) => Promise.resolve(x))); // 14
const result4 = await asyncPipe([1, 1, 1, 2, 2, 2].map((x) => Promise.resolve(x))); // 5
// Another way to create pipes
const anotherPipe = createPipe()
.add(set.distinct<number>)
.add((input) => single.map(input, (x) => x**2))
.add((input) => single.filter(input, (x) => x < 10))
.add(reduce.toSum);
const result5 = anotherPipe([1, 1, 2, 2, 3, 4, 5]); // 14
const result6 = anotherPipe([1, 1, 1, 2, 2, 2]); // 5
```
[More about Pipes](#Pipes)
All functions work on iterable collections and iterators:
* `Array`
* `Set`
* `Map`
* `String`
* `Generator`
* `Iterable`
* `Iterator`
Every function have an analog with "Async"-suffixed name for working with async iterable and iterators (e.g. `zip` and `zipAsync`):
* `AsyncIterable`
* `AsyncIterator`
If an asynchronous function takes other functions as input, they can also be asynchronous.
```typescript
import { single } from 'itertools-ts';
const starWarsEpisodes = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for await (const goodMovie of single.filterAsync(
starWarsEpisodes,
async (episode) => {
return Promise.resolve(episode > 3 && episode < 8);
}
)) {
console.log(goodMovie);
}
// 4, 5, 6, 7
```
Setup
-----
```bash
npm i itertools-ts
```
Quick Reference
---------------
### Loop Iteration Tools
#### Multi Iteration
| Iterator | Description | Sync Code Snippet | Async Code Snippet |
|------------------------------|-------------------------------------------------------------------------------------------------------------------|----------------------------------------------|---------------------------------------------------|
| [`chain`](#chain) | Chain multiple iterables together | `multi.chain(list1, list2, ...)` | `multi.chainAsync(list1, list2, ...)` |
| [`zip`](#zip) | Iterate multiple collections simultaneously until the shortest iterator completes | `multi.zip(list1, list2, ...)` | `multi.zipAsync(list1, list2, ...)` |
| [`zipEqual`](#zip-equal) | Iterate multiple collections of equal length simultaneously, error if lengths not equal | `multi.zipEqual(list1, list2, ...)` | `multi.zipEqualAsync(list1, list2, ...)` |
| [`zipFilled`](#zip-filled) | Iterate multiple collections simultaneously until the longest iterator completes (with filler for uneven lengths) | `multi.zipFilled(filler, list1, list2, ...)` | `multi.zipFilledAsync(filler, list1, list2, ...)` |
| [`zipLongest`](#zip-longest) | Iterate multiple collections simultaneously until the longest iterator completes | `multi.zipLongest(list1, list2, ...)` | `multi.zipLongestAsync(list1, list2, ...)` |
#### Single Iteration
| Iterator | Description | Sync Code Snippet | Async Code Snippet |
|------------------------------------------|---------------------------------------------|---------------------------------------------------------|--------------------------------------------------------------|
| [`chunkwise`](#chunkwise) | Iterate by chunks | `single.chunkwise(data, chunkSize)` | `single.chunkwiseAsync(data, chunkSize)` |
| [`chunkwiseOverlap`](#chunkwise-overlap) | Iterate by overlapped chunks | `single.chunkwiseOverlap(data, chunkSize, overlapSize)` | `single.chunkwiseOverlapAsync(data, chunkSize, overlapSize)` |
| [`compress`](#compress) | Filter out elements not selected | `single.compress(data, selectors)` | `single.compressAsync(data, selectors)` |
| [`dropWhile`](#drop-while) | Drop elements while predicate is true | `single.dropWhile(data, predicate)` | `single.dropWhileAsync(data, predicate)` |
| [`enumerate`](#enumerate) | Enumerates elements of collection | `single.enumerate(data)` | `single.enumerateAsync(data)` |
| [`filter`](#filter) | Filter for elements where predicate is true | `single.filter(data, predicate)` | `single.filterAsync(data, predicate)` |
| [`flatMap`](#flat-map) | Map function onto items and flatten result | `single.flatMap(data, mapper)` | `single.flatMapAsync(data, mapper)` |
| [`flatten`](#flatten) | Flatten multidimensional iterable | `single.flatten(data, [dimensions])` | `single.flattenAsync(data, [dimensions])` |
| [`groupBy`](#group-by) | Group data by a common element | `single.groupBy(data, groupKeyFunction, [itemKeyFunc])` | `single.groupByAsync(data, groupKeyFunction, [itemKeyFunc])` |
| [`limit`](#limit) | Iterate up to a limit | `single.limit(data, limit)` | `single.limitAsync(data, limit)` |
| [`keys`](#keys) | Iterate keys of key-value pairs | `single.keys(data)` | `single.keysAsync(data)` |
| [`map`](#map) | Map function onto each item | `single.map(data, mapper)` | `single.mapAsync(data, mapper)` |
| [`pairwise`](#pairwise) | Iterate successive overlapping pairs | `single.pairwise(data)` | `single.pairwiseAsync(data)` |
| [`repeat`](#repeat) | Repeat an item a number of times | `single.repeat(item, repetitions)` | `single.repeatAsync(item, repetitions)` |
| [`skip`](#skip) | Iterate after skipping elements | `single.skip(data, count, [offset])` | `single.skipAsync(data, count, [offset])` |
| [`slice`](#slice) | Extract a slice of the iterable | `single.slice(data, [start], [count], [step])` | `single.sliceAsync(data, [start], [count], [step])` |
| [`sort`](#sort) | Iterate a sorted collection | `single.sort(data, [comparator])` | `single.sortAsync(data, [comparator])` |
| [`takeWhile`](#take-while) | Iterate elements while predicate is true | `single.takeWhile(data, predicate)` | `single.takeWhileAsync(data, predicate)` |
| [`values`](#values) | Iterate values of key-value pairs | `single.values(data)` | `single.valuesAsync(data)` |
#### Infinite Iteration
| Iterator | Description | Code Snippet |
|-----------------------|----------------------------|-----------------------------------|
| [`count`](#Count) | Count sequentially forever | `infinite.count([start], [step])` |
| [`cycle`](#Cycle) | Cycle through a collection | `infinite.cycle(iterable)` |
| [`repeat`](#Repeat-1) | Repeat an item forever | `infinite.repeat(item)` |
#### Math Iteration
| Iterator | Description | Sync Code Snippet | Async Code Snippet |
|--------------------------------------------|---------------------------------|---------------------------------------------------|--------------------------------------------------------|
| [`runningAverage`](#Running-Average) | Running average accumulation | `math.runningAverage(numbers, [initialValue])` | `math.runningAverageAsync(numbers, [initialValue])` |
| [`runningDifference`](#Running-Difference) | Running difference accumulation | `math.runningDifference(numbers, [initialValue])` | `math.runningDifferenceAsync(numbers, [initialValue])` |
| [`runningMax`](#Running-Max) | Running maximum accumulation | `math.runningMax(numbers, [initialValue])` | `math.runningMax(numbers, [initialValue])` |
| [`runningMin`](#Running-Min) | Running minimum accumulation | `math.runningMin(numbers, [initialValue])` | `math.runningMinAsync(numbers, [initialValue])` |
| [`runningProduct`](#Running-Product) | Running product accumulation | `math.runningProduct(numbers, [initialValue])` | `math.runningProductAsync(numbers, [initialValue])` |
| [`runningTotal`](#Running-Total) | Running total accumulation | `math.runningTotal(numbers, [initialValue])` | `math.runningTotalAsync(numbers, [initialValue])` |
#### Reduce
| Reducer | Description | Sync Code Snippet | Async Code Snippet |
|----------------------------------------|--------------------------------------------|-----------------------------------------------|----------------------------------------------------|
| [`toAverage`](#To-Average) | Mean average of elements | `reduce.toAverage(numbers)` | `reduce.toAverageAsync(numbers)` |
| [`toCount`](#To-Count) | Reduce to length of iterable | `reduce.toCount(data)` | `reduce.toCountAsync(data)` |
| [`toFirst`](#To-First) | Reduce to its first value | `reduce.toFirst(data)` | `reduce.toFirstAsync(data)` |
| [`toFirstAndLast`](#To-First-And-Last) | Reduce to its first and last values | `reduce.toFirstAndLast(data)` | `reduce.toFirstAndLastAsync(data)` |
| [`toLast`](#To-Last) | Reduce to its last value | `reduce.toLast(data)` | `reduce.toLastAsync(data)` |
| [`toMax`](#To-Max) | Reduce to its greatest element | `reduce.toMax(numbers, [compareBy])` | `reduce.toMaxAsync(numbers, [compareBy])` |
| [`toMin`](#To-Min) | Reduce to its smallest element | `reduce.toMin(numbers, [compareBy])` | `reduce.toMinAsync(numbers, [compareBy])` |
| [`toMinMax`](#To-Min-Max) | Reduce to its lower and upper bounds | `reduce.toMinMax(numbers, [compareBy])` | `reduce.toMinMaxAsync(numbers, [compareBy])` |
| [`toProduct`](#To-Product) | Reduce to the product of its elements | `reduce.toProduct(numbers)` | `reduce.toProductAsync(numbers)` |
| [`toRange`](#To-Range) | Reduce to difference of max and min values | `reduce.toRange(numbers)` | `reduce.toRangeAsync(numbers)` |
| [`toSum`](#To-Sum) | Reduce to the sum of its elements | `reduce.toSum(numbers)` | `reduce.toSumAsync(numbers)` |
| [`toValue`](#To-Value) | Reduce to value using callable reducer | `reduce.toValue(data, reducer, initialValue)` | `reduce.toValueAsync(data, reducer, initialValue)` |
#### Set and multiset Iteration
| Iterator | Description | Sync Code Snippet | Async Code Snippet |
|------------------------------------------------|----------------------------------------|---------------------------------------------------|--------------------------------------------------------|
| [`distinct`](#distinct) | Iterate only distinct items | `set.distinct(data)` | `set.distinctAsync(data)` |
| [`intersection`](#intersection) | Intersection of iterables | `set.intersection(...iterables)` | `set.intersectionAsync(...iterables)` |
| [`partialIntersection`](#partial-intersection) | Partial intersection of iterables | `set.partialIntersection(minCount, ...iterables)` | `set.partialIntersectionAsync(minCount, ...iterables)` |
| [`symmetricDifference`](#symmetric-difference) | Symmetric difference of iterables | `set.symmetricDifference(...iterables)` | `set.symmetricDifferenceAsync(...iterables)` |
| [`union`](#union) | Union of iterables | `set.union(...iterables)` | `set.unionAsync(...iterables)` |
#### Combinatorics
| Iterator | Description | Sync Code Snippet | Async Code Snippet |
|------------------------------------------|----------------------------------------|-----------------------------------------------|----------------------------------------------------|
| [`cartesianProduct`](#cartesian-product) | Iterate cartesian product of iterables | `combinations.cartesianProduct(...iterables)` | `combinations.cartesianProductAsync(...iterables)` |
| [`combinations`](#combinations) | Combinations of iterables | `combinations.combinations(data, length)` | `combinations.combinationsAsync(data, length)` |
| [`permutations`](#permutations) | Permutations of iterables | `combinations.permutations(data, length)` | `combinations.permutationsAsync(data, length)` |
#### Summary
| Summary | Description | Sync Code Snippet | Async Code Snippet |
|-----------------------------------------|---------------------------------------------------------|----------------------------------------|---------------------------------------------|
| [`allMatch`](#all-match) | True if all items are true according to predicate | `summary.allMatch(data, predicate)` | `summary.allMatchAsync(data, predicate)` |
| [`allUnique`](#all-unique) | True if all elements in collection are unique | `summary.allUnique(data)` | `summary.allUniqueAsync(data)` |
| [`anyMatch`](#any-match) | True if any item is true according to predicate | `summary.anyMatch(data, predicate)` | `summary.anyMatchAsync(data, predicate)` |
| [`exactlyN`](#exactly-n) | True if exactly n items are true according to predicate | `summary.exactlyN(data, n, predicate)` | `summary.exactlyNAsync(data, n, predicate)` |
| [`isAsyncIterable`](#is-async-iterable) | True if given data is async iterable | `summary.isAsyncIterable(data)` | — |
| [`isIterable`](#is-iterable) | True if given data is iterable | `summary.isIterable(data)` | — |
| [`isIterator`](#is-iterator) | True if given data is iterator | `summary.isIterator(data)` | — |
| [`isReversed`](#is-reversed) | True if iterable reverse sorted | `summary.isReversed(data)` | `summary.isReversedAsync(data)` |
| [`isSorted`](#is-sorted) | True if iterable sorted | `summary.isSorted(data)` | `summary.isSortedAsync(data)` |
| [`isString`](#is-string) | True if given data is string | `summary.isString(data)` | `summary.isStringAsync(data)` |
| [`noneMatch`](#none-match) | True if none of items true according to predicate | `summary.noneMatch(data, predicate)` | `summary.noneMatchAsync(data, predicate)` |
| [`same`](#same) | True if collections are the same | `summary.same(...collections)` | `summary.sameAsync(...collections)` |
| [`sameCount`](#same-count) | True if collections have the same lengths | `summary.sameCount(...collections)` | `summary.sameCountAsync(...collections)` |
#### Transform
| Iterator | Description | Sync Code Snippet | Async Code Snippet |
|-----------------------------------------|-----------------------------------------|-----------------------------------|-----------------------------------|
| [`tee`](#tee) | Iterate duplicate iterables | `transform.tee(data, count)` | `transform.teeAsync(data, count)` |
| [`toArray`](#to-array) | Transforms collection to array | `transform.toArray(data)` | `transform.toArrayAsync(data)` |
| [`toAsyncIterable`](#to-async-iterable) | Transforms collection to async iterable | `transform.toAsyncIterable(data)` | — |
| [`toAsyncIterator`](#to-async-iterator) | Transforms collection to async iterator | `transform.toAsyncIterator(data)` | — |
| [`toIterable`](#to-iterable) | Transforms collection to iterable | `transform.toIterable(data)` | — |
| [`toIterator`](#to-iterator) | Transforms collection to iterator | `transform.toIterator(data)` | — |
| [`toMap`](#to-map) | Transforms collection to map | `transform.toMap(pairs)` | `transform.toMapAsync(pairs)` |
| [`toSet`](#to-set) | Transforms collection to set | `transform.toSet(data)` | `transform.toSetAsync(data)` |
### Stream and AsyncStream Iteration Tools
#### Stream Sources
| Source | Description | Sync Code Snippet | Async Code Snippet |
|--------------------------|-------------------------------------|-----------------------------------|----------------------------------------|
| [`of`](#of) | Create a stream from an iterable | `Stream.of(iterable)` | `AsyncStream.of(iterable)` |
| [`ofEmpty`](#of-empty) | Create an empty stream | `Stream.ofEmpty()` | `AsyncStream.ofEmpty()` |
| [`ofCount`](#of-count) | Create an infinite count stream | `Stream.ofCount([start], [step])` | `AsyncStream.ofCount([start], [step])` |
| [`ofCycle`](#of-cycle) | Create an infinite cycle stream | `Stream.ofCycle(iterable)` | `AsyncStream.ofCycle(iterable)` |
| [`ofRepeat`](#of-repeat) | Create an infinite repeating stream | `Stream.ofRepeat(item)` | `AsyncStream.ofRepeat(item)` |
#### Stream Operations
| Operation | Description | Code Snippet |
|---------------------------------------------------------|-------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [`cartesianProductWith`](#cartesian-product-with) | Iterate cartesian product of iterable source with another iterable collections | `stream.cartesianProductWith(...iterables)` |
| [`chainWith`](#chain-with) | Chain iterable source withs given iterables together into a single iteration | `stream.chainWith(...iterables)` |
| [`chunkwise`](#chunkwise-1) | Iterate by chunks | `stream.chunkwise(chunkSize)` |
| [`chunkwiseOverlap`](#chunkwise-overlap-1) | Iterate by overlapped chunks | `stream.chunkwiseOverlap(chunkSize, overlap)` |
| [`combinations`](#combinations-1) | Combinations of the stream iterable | `stream.combinations(length)` |
| [`compress`](#compress-1) | Compress source by filtering out data not selected | `stream.compress(selectors)` |
| [`distinct`](#distinct-1) | Filter out elements: iterate only unique items | `stream.distinct()` |
| [`dropWhile`](#drop-while-1) | Drop elements from the iterable source while the predicate function is true | `stream.dropWhile(predicate)` |
| [`enumerate`](#enumerate-1) | Enumerates elements of stream | `stream.enumerate()` |
| [`filter`](#filter-1) | Filter for only elements where the predicate function is true | `stream.filter(predicate)` |
| [`flatMap`](#flat-map-1) | Map function onto elements and flatten result | `stream.flatMap(mapper)` |
| [`flatten`](#flatten-1) | Flatten multidimensional stream | `stream.flatten([dimensions])` |
| [`intersectionWith`](#intersection-with) | Intersect stream and given iterables | `stream.intersectionWith(...iterables)` |
| [`groupBy`](#group-by-1) | Group stram data by a common data element | `stream.groupBy(groupKeyFunction, [itemKeyFunc])` |
| [`keys`](#keys-1) | Iterate keys of key-value pairs from stream | `stream.keys()` |
| [`limit`](#limit-1) | Limit the stream's iteration | `stream.limit(limit)` |
| [`map`](#map-1) | Map function onto elements | `stream.map(mapper)` |
| [`pairwise`](#pairwise-1) | Return pairs of elements from iterable source | `stream.pairwise()` |
| [`partialIntersectionWith`](#partial-intersection-with) | Partially intersect stream and given iterables | `stream.partialIntersectionWith(minIntersectionCount, ...iterables)` |
| [`permutations`](#permutations-1) | Permutations of the stream iterable | `stream.permutations(length)` |
| [`runningAverage`](#running-average-1) | Accumulate the running average (mean) over iterable source | `stream.runningAverage([initialValue])` |
| [`runningDifference`](#running-difference-1) | Accumulate the running difference over iterable source | `stream.runningDifference([initialValue])` |
| [`runningMax`](#running-max-1) | Accumulate the running max over iterable source | `stream.runningMax([initialValue])` |
| [`runningMin`](#running-min-1) | Accumulate the running min over iterable source | `stream.runningMin([initialValue])` |
| [`runningProduct`](#running-product-1) | Accumulate the running product over iterable source | `stream.runningProduct([initialValue])` |
| [`runningTotal`](#running-total-1) | Accumulate the running total over iterable source | `stream.runningTotal([initialValue])` |
| [`skip`](#skip-1) | Skip some elements of the stream | `stream.skip(count, [offset])` |
| [`slice`](#slice-1) | Extract a slice of the stream | `stream.slice([start], [count], [step])` |
| [`sort`](#sort-1) | Sorts the stream | `stream.sort([comparator])` |
| [`symmetricDifferenceWith`](#symmetric-difference-with) | Symmetric difference of stream and given iterables | `stream.symmetricDifferenceWith(...iterables)` |
| [`takeWhile`](#take-while-1) | Return elements from the iterable source as long as the predicate is true | `stream.takeWhile(predicate)` |
| [`unionWith`](#union-with) | Union of stream and given iterables | `stream.union(...iterables)` |
| [`values`](#values-1) | Iterate values of key-value pairs from stream | `stream.values()` |
| [`zipWith`](#zip-with) | Iterate iterable source with another iterable collections simultaneously | `stream.zipWith(...iterables)` |
| [`zipEqualWith`](#zip-equal-with) | Iterate iterable source with another iterable collections of equal lengths simultaneously | `stream.zipEqualWith(...iterables)` |
| [`zipFilledWith`](#zip-filled-with) | Iterate iterable source with another iterable collections simultaneously (with filler) | `stream.zipFilledWith(filler, ...iterables)` |
| [`zipLongestWith`](#zip-longest-with) | Iterate iterable source with another iterable collections simultaneously | `stream.zipLongestWith(...iterables)` |
#### Stream Terminal Operations
##### Transformation Terminal Operations
| Terminal Operation | Description | Code Snippet |
|--------------------------|--------------------------------------------------|---------------------|
| [`tee`](#tee-1) | Returns array of multiple identical Streams | `stream.tee(count)` |
| [`toArray`](#to-array-1) | Returns array of stream elements | `stream.toArray()` |
| [`toMap`](#to-map-1) | Returns map of stream elements (key-value pairs) | `stream.toMap()` |
| [`toSet`](#to-set-1) | Returns set of stream elements | `stream.toSet()` |
##### Reduction Terminal Operations
| Terminal Operation | Description | Code Snippet |
|------------------------------------------|----------------------------------------------------|-----------------------------------------|
| [`toAverage`](#to-average-1) | Reduces stream to the mean average of its items | `stream.toAverage()` |
| [`toCount`](#to-count-1) | Reduces stream to its length | `stream.toCount()` |
| [`toFirst`](#to-first-1) | Reduces stream to its first value | `stream.toFirst()` |
| [`toFirstAndLast`](#to-first-and-last-1) | Reduces stream to its first and last values | `stream.toFirstAndLast()` |
| [`toLast`](#to-last-1) | Reduces stream to its last value | `stream.toLast()` |
| [`toMax`](#to-max-1) | Reduces stream to its max value | `stream.toMax([compareBy])` |
| [`toMin`](#to-min-1) | Reduces stream to its min value | `stream.toMin([compareBy])` |
| [`toMin`](#to-min-max-1) | Reduce stream to its lower and upper bounds | `stream.toMinMax([compareBy])` |
| [`toProduct`](#to-product-1) | Reduces stream to the product of its items | `stream.toProduct()` |
| [`toRange`](#to-range-1) | Reduces stream to difference of max and min values | `stream.toRange()` |
| [`toSum`](#to-sum-1) | Reduces stream to the sum of its items | `stream.toSum()` |
| [`toValue`](#to-value-1) | Reduces stream like array.reduce() function | `stream.toValue(reducer, initialValue)` |
##### Summary Terminal Operations
| Terminal Operation | Description | Code Snippet |
|-------------------------------------|------------------------------------------------------------------------|----------------------------------------|
| [`allMatch`](#all-match-1) | Returns true if all items in stream match predicate | `stream.allMatch(predicate)` |
| [`allUnique`](#all-unique-1) | Returns true if all elements of stream are unique | `stream.allUnique(predicate)` |
| [`anyMatch`](#any-match-1) | Returns true if any item in stream matches predicate | `stream.anyMatch(predicate)` |
| [`exactlyN`](#exactly-n-1) | Returns true if exactly n items are true according to predicate | `stream.exactlyN(n, predicate)` |
| [`isReversed`](#is-reversed-1) | Returns true if stream is sorted in reverse descending order | `stream.isReversed()` |
| [`isSorted`](#is-sorted-1) | Returns true if stream is sorted in ascending order | `stream.isSorted()` |
| [`noneMatch`](#none-match-1) | Returns true if none of the items in stream match predicate | `stream.noneMatch(predicate)` |
| [`sameWith`](#same-with) | Returns true if stream and all given collections are the same | `stream.sameWith(...collections)` |
| [`sameCountWith`](#same-count-with) | Returns true if stream and all given collections have the same lengths | `stream.sameCountWith(...collections)` |
#### Stream Debug Operations
| Debug Operation | Description | Code Snippet |
|------------------------------|------------------------------------------------|-------------------------------|
| [`peek`](#peek) | Peek at each element between stream operations | `stream.peek(peekFunc)` |
| [`peekStream`](#peek-stream) | Peek at the entire stream between operations | `stream.peekStream(peekFunc)` |
Usage
-----
## Multi Iteration
### Chain
Chain multiple iterables together into a single continuous sequence.
```
function* chain<T>(
...iterables: Array<Iterable<T> | Iterator<T>>
): Iterable<T>
```
```typescript
import { multi } from 'itertools-ts';
const prequels = ['Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith'];
const originals = ['A New Hope', 'Empire Strikes Back', 'Return of the Jedi'];
for (const movie of multi.chain(prequels, originals)) {
console.log(movie);
}
// 'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith', 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi'
```
### Zip
Iterate multiple iterable collections simultaneously.
```
function* zip<T extends Array<Iterable<unknown> | Iterator<unknown>>>(
...iterables: T
): Iterable<ZipTuple<T, never>>
```
```typescript
import { multi } from 'itertools-ts';
const languages = ['PHP', 'Python', 'Java', 'Go'];
const mascots = ['elephant', 'snake', 'bean', 'gopher'];
for (const [language, mascot] of multi.zip(languages, mascots)) {
console.log(`The ${language} language mascot is an ${mascot}.`);
}
// The PHP language mascot is an elephant.
// ...
```
Zip works with multiple iterable inputs - not limited to just two.
```typescript
import { multi } from 'itertools-ts';
const names = ['Ryu', 'Ken', 'Chun Li', 'Guile'];
const countries = ['Japan', 'USA', 'China', 'USA'];
const signatureMoves = ['hadouken', 'shoryuken', 'spinning bird kick', 'sonic boom'];
for (const [name, country, signatureMove] of multi.zip(names, countries, signatureMoves)) {
const streetFighter = new StreetFighter(name, country, signatureMove);
}
```
Note: For uneven lengths, iteration stops when the shortest iterable is exhausted.
### Zip Filled
Iterate multiple iterable collections simultaneously.
```
function* zipFilled<T extends Array<Iterable<unknown> | Iterator<unknown>>, F>(
filler: F,
...iterables: T
): Iterable<ZipTuple<T, F>>
```
For uneven lengths, the exhausted iterables will produce `filler` value for the remaining iterations.
```typescript
import { multi } from 'itertools-ts';
const letters = ['A', 'B', 'C'];
const numbers = [1, 2];
for (const [letter, number] of multi.zipFilled('filler', letters, numbers)) {
// ['A', 1], ['B', 2], ['C', 'filler']
}
```
### Zip Longest
Iterate multiple iterable collections simultaneously.
```
function* zipLongest<T extends Array<Iterable<unknown> | Iterator<unknown>>>(
...iterables: T
): Iterable<ZipTuple<T, undefined>>
```
For uneven lengths, the exhausted iterables will produce `undefined` for the remaining iterations.
```typescript
import { multi } from 'itertools-ts';
const letters = ['A', 'B', 'C'];
const numbers = [1, 2];
for (const [letter, number] of multi.zipLongest(letters, numbers)) {
// ['A', 1], ['B', 2], ['C', undefined]
}
```
### Zip Equal
Iterate multiple iterable collections with equal lengths simultaneously.
Throws `LengthException` if lengths are not equal, meaning that at least one iterator ends before the others.
```
function* zipEqual<T extends Array<Iterable<unknown> | Iterator<unknown>>>(
...iterables: T
): Iterable<ZipTuple<T, never>>
```
```typescript
import { multi } from 'itertools-ts';
const letters = ['A', 'B', 'C'];
const numbers = [1, 2, 3];
for (const [letter, number] of multi.zipEqual(letters, numbers)) {
// ['A', 1], ['B', 2], ['C', 3]
}
```
## Single Iteration
### Chunkwise
Return elements in chunks of a certain size.
```
function* chunkwise<T>(
data: Iterable<T>|Iterator<T>,
chunkSize: number,
): Iterable<Array<T>>
```
Chunk size must be at least 1.
```typescript
import { single } from 'itertools-ts';
const movies = [
'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith',
'A New Hope', 'Empire Strikes Back', 'Return of the Jedi',
'The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker',
];
const trilogies = [];
for (const trilogy of single.chunkwise(movies, 3)) {
trilogies.push(trilogy);
}
// [
// ['Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith'],
// ['A New Hope', 'Empire Strikes Back', 'Return of the Jedi'],
// ['The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker]',
// ]
```
### Chunkwise Overlap
Return overlapped chunks of elements.
```
function* chunkwiseOverlap<T>(
data: Iterable<T>|Iterator<T>,
chunkSize: number,
overlapSize: number,
includeIncompleteTail: boolean = true,
): Iterable<Array<T>>
```
* Chunk size must be at least 1.
* Overlap size must be less than chunk size.
```typescript
import { single } from 'itertools-ts';
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const chunk of single.chunkwiseOverlap(numbers, 3, 1)) {
// [1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]
}
```
### Compress
Compress an iterable by filtering out data that is not selected.
```
function* compress<T>(
data: Iterable<T> | Iterator<T>,
selectors: Iterable<number|boolean> | Iterator<number|boolean>
): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
const movies = [
'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith',
'A New Hope', 'Empire Strikes Back', 'Return of the Jedi',
'The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker'
];
const goodMovies = [0, 0, 0, 1, 1, 1, 1, 0, 0];
for (const goodMovie of single.compress(movies, goodMovies)) {
console.log(goodMovie);
}
// 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi', 'The Force Awakens'
```
### Drop While
Drop elements from the iterable while the predicate function is true.
Once the predicate function returns false once, all remaining elements are returned.
```
function* dropWhile<T>(
data: Iterable<T>|Iterator<T>,
predicate: (item: T) => boolean
): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
const scores = [50, 60, 70, 85, 65, 90];
const predicate = (x) => x < 70;
for (const score of single.dropWhile(scores, predicate)) {
console.log(score);
}
// 70, 85, 65, 90
```
### Enumerate
Enumerates elements of given collection.
```
function* enumerate<T>(data: Iterable<T>|Iterator<T>): Iterable<[number, T]>
```
```typescript
import { single } from 'itertools-ts';
const letters = ['a', 'b', 'c', 'd', 'e'];
for (const item of single.enumerate(letters)) {
// [[0, 'a'], [1, 'b'], [2, 'c'], [3, 'd'], [4, 'e']]
}
```
### Filter
Filter out elements from the iterable only returning elements where the predicate function is true.
```
function* filter<T>(
data: Iterable<T>|Iterator<T>,
predicate: (datum: T) => boolean,
): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
const starWarsEpisodes = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const goodMoviePredicate = (episode) => episode > 3 && episode < 8;
for (const goodMovie of single.filter(starWarsEpisodes, goodMoviePredicate)) {
console.log(goodMovie);
}
// 4, 5, 6, 7
```
### Flat Map
Map a function only the elements of the iterable and then flatten the results.
```
function* flatMap<TInput, TOutput>(
data: Iterable<TInput>|Iterator<TInput>,
mapper: FlatMapper<TInput, TOutput>,
): Iterable<TOutput>
```
```typescript
import { single } from 'itertools-ts';
const data = [1, 2, 3, 4, 5];
const mapper = (item) => [item, -item];
for (number of single.flatMap(data, mapper)) {
console.log(number);
}
// 1 -1 2 -2 3 -3 4 -4 5 -5
```
### Flatten
Flatten a multidimensional iterable.
```
function* flatten(
data: Iterable<unknown>|Iterator<unknown>,
dimensions: number = Infinity,
): Iterable<unknown>
```
```typescript
import { single } from 'itertools-ts';
const multidimensional = [1, [2, 3], [4, 5]];
const flattened = [];
for (const number of single.flatten(multidimensional)) {
flattened.push(number);
}
// [1, 2, 3, 4, 5]
```
### Group By
Group data by a common data element.
Iterate pairs of group name and collection of grouped items.
```
export function* groupBy<
T,
TItemKeyFunction extends ((item: T) => string) | undefined,
TResultItem extends TItemKeyFunction extends undefined ? [string, Array<T>] : [string, Record<string, T>]
>(
data: Iterable<T> | Iterator<T>,
groupKeyFunction: (item: T) => string,
itemKeyFunction?: TItemKeyFunction
): Iterable<TResultItem>
```
* The `groupKeyFunction` determines the key to group elements by.
* The optional `itemKeyFunction` allows custom indexes within each group member.
* Collection of grouped items may be an array or an object (depends on presence of `itemKeyFunction` param).
```typescript
import { single } from 'itertools-ts';
const cartoonCharacters = [
['Garfield', 'cat'],
['Tom', 'cat'],
['Felix', 'cat'],
['Heathcliff', 'cat'],
['Snoopy', 'dog'],
['Scooby-Doo', 'dog'],
['Odie', 'dog'],
['Donald', 'duck'],
['Daffy', 'duck'],
];
const charactersGroupedByAnimal = {};
for (const [animal, characters] of single.groupBy(cartoonCharacters, (x) => x[1])) {
charactersGroupedByAnimal[animal] = characters;
}
/*
{
cat: [
['Garfield', 'cat'],
['Tom', 'cat'],
['Felix', 'cat'],
['Heathcliff', 'cat'],
],
dog: [
['Snoopy', 'dog'],
['Scooby-Doo', 'dog'],
['Odie', 'dog'],
],
duck: [
['Donald', 'duck'],
['Daffy', 'duck'],
],
}
*/
```
### Keys
Iterate keys of key-value pairs.
```
function* keys<TKey, TValue>(
collection: Iterable<[TKey, TValue]>|Iterator<[TKey, TValue]>,
): Iterable<TKey>
```
```typescript
import { single } from 'itertools-ts';
const dict = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const key of single.keys(dict)) {
console.log(key);
}
// 'a', 'b', 'c'
```
### Limit
Iterate up to a limit.
Stops even if more data available if limit reached.
```
function* limit<T>(data: Iterable<T>|Iterator<T>, count: number): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
const matrixMovies = ['The Matrix', 'The Matrix Reloaded', 'The Matrix Revolutions', 'The Matrix Resurrections'];
const limit = 1;
for (const goodMovie of single.limit(matrixMovies, limit)) {
console.log(goodMovie);
}
// 'The Matrix' (and nothing else)
```
### Map
Map a function onto each element.
```
function* map<TInput, TOutput>(
data: Iterable<TInput>|Iterator<TInput>,
mapper: (datum: TInput) => TOutput,
): Iterable<TOutput>
```
```typescript
import { single } from 'itertools-ts';
const grades = [100, 99, 95, 98, 100];
const strictParentsOpinion = (g) => (g === 100) ? 'A' : 'F';
for (const actualGrade of single.map(grades, strictParentsOpinion)) {
console.log(actualGrade);
}
// A, F, F, F, A
```
### Pairwise
Returns successive overlapping pairs.
Returns empty generator if given collection contains fewer than 2 elements.
```
function* pairwise<T>(data: Iterable<T>|Iterator<T>): Iterable<Pair<T>>
```
```typescript
import { single } from 'itertools-ts';
const friends = ['Ross', 'Rachel', 'Chandler', 'Monica', 'Joey', 'Phoebe'];
for (const [leftFriend, rightFriend] of single.pairwise(friends)) {
console.log(`${leftFriend} and ${rightFriend}`);
}
// Ross and Rachel, Rachel and Chandler, Chandler and Monica, ...
```
### Repeat
Repeat an item.
```
function* repeat<T>(item: T, repetitions: number): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
data = 'Beetlejuice';
repetitions = 3;
for (const repeated of single.repeat(data, repetitions)) {
console.log(repeated);
}
// 'Beetlejuice', 'Beetlejuice', 'Beetlejuice'
```
### Skip
Skip n elements in the iterable after optional offset offset.
```
function* skip<T>(
data: Iterable<T> | Iterator<T>,
count: number,
offset: number = 0
): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
const movies = [
'The Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith',
'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi',
'The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker'
];
const prequelsRemoved = [];
for (const nonPrequel of Single.skip(movies, 3)) {
prequelsRemoved.push(nonPrequel);
} // Episodes IV - IX
const onlyTheBest = [];
for (const nonSequel of Single.skip(prequelsRemoved, 3, 3)) {
onlyTheBest.push(nonSequel);
}
// 'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi'
```
### Slice
Extract a slice of the iterable.
```
function* slice<T>(
data: Iterable<T>|Iterator<T>,
start: number = 0,
count?: number,
step: number = 1,
): Iterable<T>
```
```typescript
import { single } from 'itertools-ts';
const olympics = [1992, 1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020, 2022];
const winterOlympics = [];
for (const winterYear of single.slice(olympics, 1, 8, 2)) {
winterOlympics.push(winterYear);
}
// [1994, 1998, 2002, 2006, 2010, 2014, 2018, 2022]
```
### Sort
Iterate the collection sorted.
```
function* sort<T>(
data: Iterable<T> | Iterator<T>,
comparator?: Comparator<T>,
): Iterable<T>
```
Uses default sorting if optional comparator function not provided.
```typescript
import { single } from 'itertools-ts';
const data = [3, 4, 5, 9, 8, 7, 1, 6, 2];
for (const datum of single.sort(data)) {
console.log(datum);
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9
```
### Take While
Return elements from the iterable as long as the predicate is true.
Stops iteration as soon as the predicate returns false, even if other elements later on would eventually return true (different from filterTrue).
```
function* takeWhile<T>(
data: Iterable<T> | Iterator<T>,
predicate: (item: T)