Installations
npm install itertools-ts
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
22.13.1
NPM Version
10.9.2
Releases
combinatorics.combinations() added
Published on 30 Jan 2025
New namespace added: combinatorics
Published on 29 Jan 2025
Stream and AsyncStream made generics to save the typing
Published on 25 Jan 2025
Union return type in groupBy replaced by inferred type
Published on 23 Jan 2025
Pipe.add() method added
Published on 23 Dec 2024
Documentation fixed
Published on 23 Dec 2024
Contributors
Languages
TypeScript (100%)
Developer
Download Statistics
Total Downloads
20,568
Last Day
108
Last Week
374
Last Month
1,262
Last Year
7,506
GitHub Statistics
55 Stars
375 Commits
7 Forks
3 Watching
2 Branches
3 Contributors
Bundle Size
58.49 kB
Minified
10.13 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.2.0
Package Id
itertools-ts@2.2.0
Unpacked Size
1.68 MB
Size
216.89 kB
File Count
122
NPM Version
10.9.2
Node Version
22.13.1
Publised On
30 Jan 2025
Total Downloads
Cumulative downloads
Total Downloads
20,568
Last day
237.5%
108
Compared to previous day
Last week
31.2%
374
Compared to previous week
Last month
66.3%
1,262
Compared to previous month
Last year
-42.5%
7,506
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
IterTools for TypeScript and JavaScript
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
1import { multi } from 'itertools-ts'; 2 3for (const [letter, number] of multi.zip(['a', 'b'], [1, 2])) { 4 console.log(`${letter}${number}`); // a1, b2 5} 6 7// Async example 8const letters = ['a', 'b'].map((x) => Promise.resolve(x)); 9const numbers = [1, 2].map((x) => Promise.resolve(x)); 10 11for await (const [letter, number] of multi.zipAsync(letters, numbers)) { 12 console.log(`${letter}${number}`); // a1, b2 13}
Stream Iteration Tools Example
1import { Stream, AsyncStream } from 'itertools-ts'; 2 3const result1 = Stream.of([1, 1, 2, 2, 3, 4, 5]) 4 .distinct() // [1, 2, 3, 4, 5] 5 .map((x) => x**2) // [1, 4, 9, 16, 25] 6 .filter((x) => x < 10) // [1, 4, 9] 7 .toSum(); // 14 8 9// Async example 10const result2 = await AsyncStream.of([1, 1, 2, 2, 3, 4, 5].map((x) => Promise.resolve(x))) 11 .distinct() // [1, 2, 3, 4, 5] 12 .map((x) => x**2) // [1, 4, 9, 16, 25] 13 .filter((x) => x < 10) // [1, 4, 9] 14 .toSum(); // 14
Pipe Iteration Tools Example
1import { createPipe } from 'itertools-ts'; 2 3const pipe = createPipe( 4 set.distinct<number>, 5 (input) => single.map(input, (x) => x**2), 6 (input) => single.filter(input, (x) => x < 10), 7 reduce.toSum, 8); 9const result1 = pipe([1, 1, 2, 2, 3, 4, 5]); // 14 10const result2 = pipe([1, 1, 1, 2, 2, 2]); // 5 11 12// Async example 13const asyncPipe = createPipe( 14 set.distinctAsync<number>, 15 (input) => single.mapAsync(input, (x) => x**2), 16 (input) => single.filterAsync(input, (x) => x < 10), 17 reduce.toSumAsync, 18); 19const result3 = await asyncPipe([1, 1, 2, 2, 3, 4, 5].map((x) => Promise.resolve(x))); // 14 20const result4 = await asyncPipe([1, 1, 1, 2, 2, 2].map((x) => Promise.resolve(x))); // 5 21 22// Another way to create pipes 23const anotherPipe = createPipe() 24 .add(set.distinct<number>) 25 .add((input) => single.map(input, (x) => x**2)) 26 .add((input) => single.filter(input, (x) => x < 10)) 27 .add(reduce.toSum); 28 29const result5 = anotherPipe([1, 1, 2, 2, 3, 4, 5]); // 14 30const result6 = anotherPipe([1, 1, 1, 2, 2, 2]); // 5
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.
1import { single } from 'itertools-ts'; 2 3const starWarsEpisodes = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 4 5for await (const goodMovie of single.filterAsync( 6 starWarsEpisodes, 7 async (episode) => { 8 return Promise.resolve(episode > 3 && episode < 8); 9 } 10)) { 11 console.log(goodMovie); 12} 13// 4, 5, 6, 7
Setup
1npm i itertools-ts
Quick Reference
Loop Iteration Tools
Multi Iteration
Iterator | Description | Sync Code Snippet | Async Code Snippet |
---|---|---|---|
chain | Chain multiple iterables together | multi.chain(list1, list2, ...) | multi.chainAsync(list1, list2, ...) |
zip | Iterate multiple collections simultaneously until the shortest iterator completes | multi.zip(list1, list2, ...) | multi.zipAsync(list1, list2, ...) |
zipEqual | Iterate multiple collections of equal length simultaneously, error if lengths not equal | multi.zipEqual(list1, list2, ...) | multi.zipEqualAsync(list1, list2, ...) |
zipFilled | 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 | 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 | Iterate by chunks | single.chunkwise(data, chunkSize) | single.chunkwiseAsync(data, chunkSize) |
chunkwiseOverlap | Iterate by overlapped chunks | single.chunkwiseOverlap(data, chunkSize, overlapSize) | single.chunkwiseOverlapAsync(data, chunkSize, overlapSize) |
compress | Filter out elements not selected | single.compress(data, selectors) | single.compressAsync(data, selectors) |
dropWhile | Drop elements while predicate is true | single.dropWhile(data, predicate) | single.dropWhileAsync(data, predicate) |
enumerate | Enumerates elements of collection | single.enumerate(data) | single.enumerateAsync(data) |
filter | Filter for elements where predicate is true | single.filter(data, predicate) | single.filterAsync(data, predicate) |
flatMap | Map function onto items and flatten result | single.flatMap(data, mapper) | single.flatMapAsync(data, mapper) |
flatten | Flatten multidimensional iterable | single.flatten(data, [dimensions]) | single.flattenAsync(data, [dimensions]) |
groupBy | Group data by a common element | single.groupBy(data, groupKeyFunction, [itemKeyFunc]) | single.groupByAsync(data, groupKeyFunction, [itemKeyFunc]) |
limit | Iterate up to a limit | single.limit(data, limit) | single.limitAsync(data, limit) |
keys | Iterate keys of key-value pairs | single.keys(data) | single.keysAsync(data) |
map | Map function onto each item | single.map(data, mapper) | single.mapAsync(data, mapper) |
pairwise | Iterate successive overlapping pairs | single.pairwise(data) | single.pairwiseAsync(data) |
repeat | Repeat an item a number of times | single.repeat(item, repetitions) | single.repeatAsync(item, repetitions) |
skip | Iterate after skipping elements | single.skip(data, count, [offset]) | single.skipAsync(data, count, [offset]) |
slice | Extract a slice of the iterable | single.slice(data, [start], [count], [step]) | single.sliceAsync(data, [start], [count], [step]) |
sort | Iterate a sorted collection | single.sort(data, [comparator]) | single.sortAsync(data, [comparator]) |
takeWhile | Iterate elements while predicate is true | single.takeWhile(data, predicate) | single.takeWhileAsync(data, predicate) |
values | Iterate values of key-value pairs | single.values(data) | single.valuesAsync(data) |
Infinite Iteration
Iterator | Description | Code Snippet |
---|---|---|
count | Count sequentially forever | infinite.count([start], [step]) |
cycle | Cycle through a collection | infinite.cycle(iterable) |
repeat | Repeat an item forever | infinite.repeat(item) |
Math Iteration
Iterator | Description | Sync Code Snippet | Async Code Snippet |
---|---|---|---|
runningAverage | Running average accumulation | math.runningAverage(numbers, [initialValue]) | math.runningAverageAsync(numbers, [initialValue]) |
runningDifference | Running difference accumulation | math.runningDifference(numbers, [initialValue]) | math.runningDifferenceAsync(numbers, [initialValue]) |
runningMax | Running maximum accumulation | math.runningMax(numbers, [initialValue]) | math.runningMax(numbers, [initialValue]) |
runningMin | Running minimum accumulation | math.runningMin(numbers, [initialValue]) | math.runningMinAsync(numbers, [initialValue]) |
runningProduct | Running product accumulation | math.runningProduct(numbers, [initialValue]) | math.runningProductAsync(numbers, [initialValue]) |
runningTotal | Running total accumulation | math.runningTotal(numbers, [initialValue]) | math.runningTotalAsync(numbers, [initialValue]) |
Reduce
Reducer | Description | Sync Code Snippet | Async Code Snippet |
---|---|---|---|
toAverage | Mean average of elements | reduce.toAverage(numbers) | reduce.toAverageAsync(numbers) |
toCount | Reduce to length of iterable | reduce.toCount(data) | reduce.toCountAsync(data) |
toFirst | Reduce to its first value | reduce.toFirst(data) | reduce.toFirstAsync(data) |
toFirstAndLast | Reduce to its first and last values | reduce.toFirstAndLast(data) | reduce.toFirstAndLastAsync(data) |
toLast | Reduce to its last value | reduce.toLast(data) | reduce.toLastAsync(data) |
toMax | Reduce to its greatest element | reduce.toMax(numbers, [compareBy]) | reduce.toMaxAsync(numbers, [compareBy]) |
toMin | Reduce to its smallest element | reduce.toMin(numbers, [compareBy]) | reduce.toMinAsync(numbers, [compareBy]) |
toMinMax | Reduce to its lower and upper bounds | reduce.toMinMax(numbers, [compareBy]) | reduce.toMinMaxAsync(numbers, [compareBy]) |
toProduct | Reduce to the product of its elements | reduce.toProduct(numbers) | reduce.toProductAsync(numbers) |
toRange | Reduce to difference of max and min values | reduce.toRange(numbers) | reduce.toRangeAsync(numbers) |
toSum | Reduce to the sum of its elements | reduce.toSum(numbers) | reduce.toSumAsync(numbers) |
toValue | 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 | Iterate only distinct items | set.distinct(data) | set.distinctAsync(data) |
intersection | Intersection of iterables | set.intersection(...iterables) | set.intersectionAsync(...iterables) |
partialIntersection | Partial intersection of iterables | set.partialIntersection(minCount, ...iterables) | set.partialIntersectionAsync(minCount, ...iterables) |
symmetricDifference | Symmetric difference of iterables | set.symmetricDifference(...iterables) | set.symmetricDifferenceAsync(...iterables) |
union | Union of iterables | set.union(...iterables) | set.unionAsync(...iterables) |
Combinatorics
Iterator | Description | Sync Code Snippet | Async Code Snippet |
---|---|---|---|
cartesianProduct | Iterate cartesian product of iterables | combinations.cartesianProduct(...iterables) | combinations.cartesianProductAsync(...iterables) |
combinations | Combinations of iterables | combinations.combinations(data, length) | combinations.combinationsAsync(data, length) |
permutations | Permutations of iterables | combinations.permutations(data, length) | combinations.permutationsAsync(data, length) |
Summary
Summary | Description | Sync Code Snippet | Async Code Snippet |
---|---|---|---|
allMatch | True if all items are true according to predicate | summary.allMatch(data, predicate) | summary.allMatchAsync(data, predicate) |
allUnique | True if all elements in collection are unique | summary.allUnique(data) | summary.allUniqueAsync(data) |
anyMatch | True if any item is true according to predicate | summary.anyMatch(data, predicate) | summary.anyMatchAsync(data, predicate) |
exactlyN | True if exactly n items are true according to predicate | summary.exactlyN(data, n, predicate) | summary.exactlyNAsync(data, n, predicate) |
isAsyncIterable | True if given data is async iterable | summary.isAsyncIterable(data) | — |
isIterable | True if given data is iterable | summary.isIterable(data) | — |
isIterator | True if given data is iterator | summary.isIterator(data) | — |
isReversed | True if iterable reverse sorted | summary.isReversed(data) | summary.isReversedAsync(data) |
isSorted | True if iterable sorted | summary.isSorted(data) | summary.isSortedAsync(data) |
isString | True if given data is string | summary.isString(data) | summary.isStringAsync(data) |
noneMatch | True if none of items true according to predicate | summary.noneMatch(data, predicate) | summary.noneMatchAsync(data, predicate) |
same | True if collections are the same | summary.same(...collections) | summary.sameAsync(...collections) |
sameCount | True if collections have the same lengths | summary.sameCount(...collections) | summary.sameCountAsync(...collections) |
Transform
Iterator | Description | Sync Code Snippet | Async Code Snippet |
---|---|---|---|
tee | Iterate duplicate iterables | transform.tee(data, count) | transform.teeAsync(data, count) |
toArray | Transforms collection to array | transform.toArray(data) | transform.toArrayAsync(data) |
toAsyncIterable | Transforms collection to async iterable | transform.toAsyncIterable(data) | — |
toAsyncIterator | Transforms collection to async iterator | transform.toAsyncIterator(data) | — |
toIterable | Transforms collection to iterable | transform.toIterable(data) | — |
toIterator | Transforms collection to iterator | transform.toIterator(data) | — |
toMap | Transforms collection to map | transform.toMap(pairs) | transform.toMapAsync(pairs) |
toSet | 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 | Create a stream from an iterable | Stream.of(iterable) | AsyncStream.of(iterable) |
ofEmpty | Create an empty stream | Stream.ofEmpty() | AsyncStream.ofEmpty() |
ofCount | Create an infinite count stream | Stream.ofCount([start], [step]) | AsyncStream.ofCount([start], [step]) |
ofCycle | Create an infinite cycle stream | Stream.ofCycle(iterable) | AsyncStream.ofCycle(iterable) |
ofRepeat | Create an infinite repeating stream | Stream.ofRepeat(item) | AsyncStream.ofRepeat(item) |
Stream Operations
Operation | Description | Code Snippet |
---|---|---|
cartesianProductWith | Iterate cartesian product of iterable source with another iterable collections | stream.cartesianProductWith(...iterables) |
chainWith | Chain iterable source withs given iterables together into a single iteration | stream.chainWith(...iterables) |
chunkwise | Iterate by chunks | stream.chunkwise(chunkSize) |
chunkwiseOverlap | Iterate by overlapped chunks | stream.chunkwiseOverlap(chunkSize, overlap) |
combinations | Combinations of the stream iterable | stream.combinations(length) |
compress | Compress source by filtering out data not selected | stream.compress(selectors) |
distinct | Filter out elements: iterate only unique items | stream.distinct() |
dropWhile | Drop elements from the iterable source while the predicate function is true | stream.dropWhile(predicate) |
enumerate | Enumerates elements of stream | stream.enumerate() |
filter | Filter for only elements where the predicate function is true | stream.filter(predicate) |
flatMap | Map function onto elements and flatten result | stream.flatMap(mapper) |
flatten | Flatten multidimensional stream | stream.flatten([dimensions]) |
intersectionWith | Intersect stream and given iterables | stream.intersectionWith(...iterables) |
groupBy | Group stram data by a common data element | stream.groupBy(groupKeyFunction, [itemKeyFunc]) |
keys | Iterate keys of key-value pairs from stream | stream.keys() |
limit | Limit the stream's iteration | stream.limit(limit) |
map | Map function onto elements | stream.map(mapper) |
pairwise | Return pairs of elements from iterable source | stream.pairwise() |
partialIntersectionWith | Partially intersect stream and given iterables | stream.partialIntersectionWith(minIntersectionCount, ...iterables) |
permutations | Permutations of the stream iterable | stream.permutations(length) |
runningAverage | Accumulate the running average (mean) over iterable source | stream.runningAverage([initialValue]) |
runningDifference | Accumulate the running difference over iterable source | stream.runningDifference([initialValue]) |
runningMax | Accumulate the running max over iterable source | stream.runningMax([initialValue]) |
runningMin | Accumulate the running min over iterable source | stream.runningMin([initialValue]) |
runningProduct | Accumulate the running product over iterable source | stream.runningProduct([initialValue]) |
runningTotal | Accumulate the running total over iterable source | stream.runningTotal([initialValue]) |
skip | Skip some elements of the stream | stream.skip(count, [offset]) |
slice | Extract a slice of the stream | stream.slice([start], [count], [step]) |
sort | Sorts the stream | stream.sort([comparator]) |
symmetricDifferenceWith | Symmetric difference of stream and given iterables | stream.symmetricDifferenceWith(...iterables) |
takeWhile | Return elements from the iterable source as long as the predicate is true | stream.takeWhile(predicate) |
unionWith | Union of stream and given iterables | stream.union(...iterables) |
values | Iterate values of key-value pairs from stream | stream.values() |
zipWith | Iterate iterable source with another iterable collections simultaneously | stream.zipWith(...iterables) |
zipEqualWith | Iterate iterable source with another iterable collections of equal lengths simultaneously | stream.zipEqualWith(...iterables) |
zipFilledWith | Iterate iterable source with another iterable collections simultaneously (with filler) | stream.zipFilledWith(filler, ...iterables) |
zipLongestWith | Iterate iterable source with another iterable collections simultaneously | stream.zipLongestWith(...iterables) |
Stream Terminal Operations
Transformation Terminal Operations
Terminal Operation | Description | Code Snippet |
---|---|---|
tee | Returns array of multiple identical Streams | stream.tee(count) |
toArray | Returns array of stream elements | stream.toArray() |
toMap | Returns map of stream elements (key-value pairs) | stream.toMap() |
toSet | Returns set of stream elements | stream.toSet() |
Reduction Terminal Operations
Terminal Operation | Description | Code Snippet |
---|---|---|
toAverage | Reduces stream to the mean average of its items | stream.toAverage() |
toCount | Reduces stream to its length | stream.toCount() |
toFirst | Reduces stream to its first value | stream.toFirst() |
toFirstAndLast | Reduces stream to its first and last values | stream.toFirstAndLast() |
toLast | Reduces stream to its last value | stream.toLast() |
toMax | Reduces stream to its max value | stream.toMax([compareBy]) |
toMin | Reduces stream to its min value | stream.toMin([compareBy]) |
toMin | Reduce stream to its lower and upper bounds | stream.toMinMax([compareBy]) |
toProduct | Reduces stream to the product of its items | stream.toProduct() |
toRange | Reduces stream to difference of max and min values | stream.toRange() |
toSum | Reduces stream to the sum of its items | stream.toSum() |
toValue | Reduces stream like array.reduce() function | stream.toValue(reducer, initialValue) |
Summary Terminal Operations
Terminal Operation | Description | Code Snippet |
---|---|---|
allMatch | Returns true if all items in stream match predicate | stream.allMatch(predicate) |
allUnique | Returns true if all elements of stream are unique | stream.allUnique(predicate) |
anyMatch | Returns true if any item in stream matches predicate | stream.anyMatch(predicate) |
exactlyN | Returns true if exactly n items are true according to predicate | stream.exactlyN(n, predicate) |
isReversed | Returns true if stream is sorted in reverse descending order | stream.isReversed() |
isSorted | Returns true if stream is sorted in ascending order | stream.isSorted() |
noneMatch | Returns true if none of the items in stream match predicate | stream.noneMatch(predicate) |
sameWith | Returns true if stream and all given collections are the same | stream.sameWith(...collections) |
sameCountWith | 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 at each element between stream operations | stream.peek(peekFunc) |
peekStream | 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>
1import { multi } from 'itertools-ts'; 2 3const prequels = ['Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith']; 4const originals = ['A New Hope', 'Empire Strikes Back', 'Return of the Jedi']; 5 6for (const movie of multi.chain(prequels, originals)) { 7 console.log(movie); 8} 9// '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>>
1import { multi } from 'itertools-ts'; 2 3const languages = ['PHP', 'Python', 'Java', 'Go']; 4const mascots = ['elephant', 'snake', 'bean', 'gopher']; 5 6for (const [language, mascot] of multi.zip(languages, mascots)) { 7 console.log(`The ${language} language mascot is an ${mascot}.`); 8} 9// The PHP language mascot is an elephant. 10// ...
Zip works with multiple iterable inputs - not limited to just two.
1import { multi } from 'itertools-ts'; 2 3const names = ['Ryu', 'Ken', 'Chun Li', 'Guile']; 4const countries = ['Japan', 'USA', 'China', 'USA']; 5const signatureMoves = ['hadouken', 'shoryuken', 'spinning bird kick', 'sonic boom']; 6 7for (const [name, country, signatureMove] of multi.zip(names, countries, signatureMoves)) { 8 const streetFighter = new StreetFighter(name, country, signatureMove); 9}
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.
1import { multi } from 'itertools-ts'; 2 3const letters = ['A', 'B', 'C']; 4const numbers = [1, 2]; 5 6for (const [letter, number] of multi.zipFilled('filler', letters, numbers)) { 7 // ['A', 1], ['B', 2], ['C', 'filler'] 8}
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.
1import { multi } from 'itertools-ts'; 2 3const letters = ['A', 'B', 'C']; 4const numbers = [1, 2]; 5 6for (const [letter, number] of multi.zipLongest(letters, numbers)) { 7 // ['A', 1], ['B', 2], ['C', undefined] 8}
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>>
1import { multi } from 'itertools-ts'; 2 3const letters = ['A', 'B', 'C']; 4const numbers = [1, 2, 3]; 5 6for (const [letter, number] of multi.zipEqual(letters, numbers)) { 7 // ['A', 1], ['B', 2], ['C', 3] 8}
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.
1import { single } from 'itertools-ts'; 2 3const movies = [ 4 'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith', 5 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi', 6 'The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker', 7]; 8const trilogies = []; 9 10for (const trilogy of single.chunkwise(movies, 3)) { 11 trilogies.push(trilogy); 12} 13// [ 14// ['Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith'], 15// ['A New Hope', 'Empire Strikes Back', 'Return of the Jedi'], 16// ['The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker]', 17// ]
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.
1import { single } from 'itertools-ts'; 2 3const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 4 5for (const chunk of single.chunkwiseOverlap(numbers, 3, 1)) { 6 // [1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10] 7}
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>
1import { single } from 'itertools-ts'; 2 3const movies = [ 4 'Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith', 5 'A New Hope', 'Empire Strikes Back', 'Return of the Jedi', 6 'The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker' 7]; 8const goodMovies = [0, 0, 0, 1, 1, 1, 1, 0, 0]; 9 10for (const goodMovie of single.compress(movies, goodMovies)) { 11 console.log(goodMovie); 12} 13// '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>
1import { single } from 'itertools-ts'; 2 3const scores = [50, 60, 70, 85, 65, 90]; 4const predicate = (x) => x < 70; 5 6for (const score of single.dropWhile(scores, predicate)) { 7 console.log(score); 8} 9// 70, 85, 65, 90
Enumerate
Enumerates elements of given collection.
function* enumerate<T>(data: Iterable<T>|Iterator<T>): Iterable<[number, T]>
1import { single } from 'itertools-ts'; 2 3const letters = ['a', 'b', 'c', 'd', 'e']; 4 5for (const item of single.enumerate(letters)) { 6 // [[0, 'a'], [1, 'b'], [2, 'c'], [3, 'd'], [4, 'e']] 7}
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>
1import { single } from 'itertools-ts'; 2 3const starWarsEpisodes = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 4const goodMoviePredicate = (episode) => episode > 3 && episode < 8; 5 6for (const goodMovie of single.filter(starWarsEpisodes, goodMoviePredicate)) { 7 console.log(goodMovie); 8} 9// 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>
1import { single } from 'itertools-ts'; 2 3const data = [1, 2, 3, 4, 5]; 4const mapper = (item) => [item, -item]; 5 6for (number of single.flatMap(data, mapper)) { 7 console.log(number); 8} 9// 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>
1import { single } from 'itertools-ts'; 2 3const multidimensional = [1, [2, 3], [4, 5]]; 4 5const flattened = []; 6for (const number of single.flatten(multidimensional)) { 7 flattened.push(number); 8} 9// [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).
1import { single } from 'itertools-ts'; 2 3const cartoonCharacters = [ 4 ['Garfield', 'cat'], 5 ['Tom', 'cat'], 6 ['Felix', 'cat'], 7 ['Heathcliff', 'cat'], 8 ['Snoopy', 'dog'], 9 ['Scooby-Doo', 'dog'], 10 ['Odie', 'dog'], 11 ['Donald', 'duck'], 12 ['Daffy', 'duck'], 13]; 14 15const charactersGroupedByAnimal = {}; 16for (const [animal, characters] of single.groupBy(cartoonCharacters, (x) => x[1])) { 17 charactersGroupedByAnimal[animal] = characters; 18} 19/* 20{ 21 cat: [ 22 ['Garfield', 'cat'], 23 ['Tom', 'cat'], 24 ['Felix', 'cat'], 25 ['Heathcliff', 'cat'], 26 ], 27 dog: [ 28 ['Snoopy', 'dog'], 29 ['Scooby-Doo', 'dog'], 30 ['Odie', 'dog'], 31 ], 32 duck: [ 33 ['Donald', 'duck'], 34 ['Daffy', 'duck'], 35 ], 36} 37*/
Keys
Iterate keys of key-value pairs.
function* keys<TKey, TValue>(
collection: Iterable<[TKey, TValue]>|Iterator<[TKey, TValue]>,
): Iterable<TKey>
1import { single } from 'itertools-ts'; 2 3const dict = new Map([['a', 1], ['b', 2], ['c', 3]]); 4 5for (const key of single.keys(dict)) { 6 console.log(key); 7} 8// '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>
1import { single } from 'itertools-ts'; 2 3const matrixMovies = ['The Matrix', 'The Matrix Reloaded', 'The Matrix Revolutions', 'The Matrix Resurrections']; 4const limit = 1; 5 6for (const goodMovie of single.limit(matrixMovies, limit)) { 7 console.log(goodMovie); 8} 9// '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>
1import { single } from 'itertools-ts'; 2 3const grades = [100, 99, 95, 98, 100]; 4const strictParentsOpinion = (g) => (g === 100) ? 'A' : 'F'; 5 6for (const actualGrade of single.map(grades, strictParentsOpinion)) { 7 console.log(actualGrade); 8} 9// 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>>
1import { single } from 'itertools-ts'; 2 3const friends = ['Ross', 'Rachel', 'Chandler', 'Monica', 'Joey', 'Phoebe']; 4 5for (const [leftFriend, rightFriend] of single.pairwise(friends)) { 6 console.log(`${leftFriend} and ${rightFriend}`); 7} 8// Ross and Rachel, Rachel and Chandler, Chandler and Monica, ...
Repeat
Repeat an item.
function* repeat<T>(item: T, repetitions: number): Iterable<T>
1import { single } from 'itertools-ts'; 2 3data = 'Beetlejuice'; 4repetitions = 3; 5 6for (const repeated of single.repeat(data, repetitions)) { 7 console.log(repeated); 8} 9// '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>
1import { single } from 'itertools-ts'; 2 3const movies = [ 4 'The Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith', 5 'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi', 6 'The Force Awakens', 'The Last Jedi', 'The Rise of Skywalker' 7]; 8 9const prequelsRemoved = []; 10for (const nonPrequel of Single.skip(movies, 3)) { 11 prequelsRemoved.push(nonPrequel); 12} // Episodes IV - IX 13 14const onlyTheBest = []; 15for (const nonSequel of Single.skip(prequelsRemoved, 3, 3)) { 16 onlyTheBest.push(nonSequel); 17} 18// '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>
1import { single } from 'itertools-ts'; 2 3const olympics = [1992, 1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020, 2022]; 4const winterOlympics = []; 5 6for (const winterYear of single.slice(olympics, 1, 8, 2)) { 7 winterOlympics.push(winterYear); 8} 9// [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.
1import { single } from 'itertools-ts'; 2 3const data = [3, 4, 5, 9, 8, 7, 1, 6, 2]; 4 5for (const datum of single.sort(data)) { 6 console.log(datum); 7} 8// 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) => boolean
): Iterable<T>
1import { single } from 'itertools-ts'; 2 3const prices = [0, 0, 5, 10, 0, 0, 9]; 4const isFree = (price) => price == 0; 5 6for (const freePrice of single.takeWhile(prices, isFree)) { 7 console.log(freePrice); 8} 9// 0, 0
Values
Iterate values of key-value pairs.
function* values<TKey, TValue>(
collection: Iterable<[TKey, TValue]>|Iterator<[TKey, TValue]>,
): Iterable<TValue>
1import { single } from 'itertools-ts'; 2 3const dict = new Map([['a', 1], ['b', 2], ['c', 3]]); 4 5for (const value of single.keys(dict)) { 6 console.log(value); 7} 8// 1, 2, 3
Infinite Iteration
Count
Count sequentially forever.
function* count(start: number = 1, step: number = 1): Iterable<number>
1import { infinite } from 'itertools-ts'; 2 3for (const i of infinite.count()) { 4 console.log(i); 5} 6// 1, 2, 3, 4, 5, ...
Cycle
Cycle through the elements of a collection sequentially forever.
function* cycle<T>(iterable: Iterable<T> | Iterator<T>): Iterable<T>
1import { infinite } from 'itertools-ts'; 2 3for (const item of infinite.cycle(['rock', 'paper', 'scissors'])) { 4 console.log(item); 5} 6// 'rock', 'paper', 'scissors', 'rock', 'paper', 'scissors', 'rock', ...
Repeat
Repeat an item forever.
function* repeat<T>(item: T): Iterable<T>
1import { infinite } from 'itertools-ts'; 2 3for (const item of infinite.repeat('bla')) { 4 console.log(item); 5} 6// bla, bla, bla, bla, bla, ...
Math Iteration
Running Average
Accumulate the running average over a list of numbers.
function* runningAverage(
numbers: Iterable<Numeric> | Iterator<Numeric>,
initialValue?: number
): Iterable<number>
1import { math } from 'itertools-ts'; 2 3const grades = [100, 80, 80, 90, 85]; 4 5for (const runningAverage of math.runningAverage(grades)) { 6 console.log(runningAverage); 7} 8// 100, 90, 86.667, 87.5, 87
Running Difference
Accumulate the running difference over a list of numbers.
function* runningDifference(
numbers: Iterable<Numeric> | Iterator<Numeric>,
initialValue?: number
): Iterable<number>
1import { math } from 'itertools-ts'; 2 3const credits = [1, 2, 3, 4, 5]; 4 5for (const runningDifference of math.runningDifference(credits)) { 6 console.log(runningDifference); 7} 8// -1, -3, -6, -10, -15
Provide an optional initial value to lead off the running difference.
1import { math } from 'itertools-ts'; 2 3const dartsScores = [50, 50, 25, 50]; 4const startingScore = 501; 5 6for (const runningScore of math.runningDifference(dartsScores, startingScore)) { 7 console.log(runningScore); 8} 9// 501, 451, 401, 376, 326
Running Max
Accumulate the running maximum over a list of numbers.
function* runningMax(
numbers: Iterable<Numeric> | Iterator<Numeric>,
initialValue?: number
): Iterable<number>
1import { math } from 'itertools-ts'; 2 3const numbers = [1, 2, 1, 3, 5]; 4 5for (const runningMax of math.runningMax(numbers)) { 6 console.log(runningMax); 7} 8// 1, 2, 2, 3, 5
Running Min
Accumulate the running minimum over a list of numbers.
function* runningMin(
numbers: Iterable<Numeric> | Iterator<Numeric>,
initialValue?: number
): Iterable<number>
1import { math } from 'itertools-ts'; 2 3const numbers = [3, 4, 2, 5, 1]; 4 5for (const runningMin of math.runningMin(numbers)) { 6 console.log(runningMin); 7} 8// 3, 3, 2, 2, 1
Running Product
Accumulate the running product over a list of numbers.
function* runningProduct(
numbers: Iterable<Numeric> | Iterator<Numeric>,
initialValue?: number
): Iterable<number>
1import { math } from 'itertools-ts'; 2 3const numbers = [1, 2, 3, 4, 5]; 4 5for (const runningProduct of math.runningProduct(numbers)) { 6 console.log(runningProduct); 7} 8// 1, 2, 6, 24, 120
Provide an optional initial value to lead off the running product.
1import { math } from 'itertools-ts'; 2 3const numbers = [1, 2, 3, 4, 5]; 4const initialValue = 5; 5 6for (const runningProduct of math.runningProduct(numbers, initialValue)) { 7 console.log(runningProduct); 8} 9// 5, 5, 10, 30, 120, 600
Running Total
Accumulate the running total over a list of numbers.
function* runningTotal(
numbers: Iterable<Numeric> | Iterator<Numeric>,
initialValue?: number
): Iterable<number>
1import { math } from 'itertools-ts'; 2 3const prices = [1, 2, 3, 4, 5]; 4 5for (const runningTotal of math.runningTotal(prices)) { 6 console.log(runningTotal); 7} 8// 1, 3, 6, 10, 15
Provide an optional initial value to lead off the running total.
1import { math } from 'itertools-ts'; 2 3const prices = [1, 2, 3, 4, 5]; 4const initialValue = 5; 5 6for (const runningTotal of math.runningTotal(prices, initialValue)) { 7 console.log(runningTotal); 8} 9// 5, 6, 8, 11, 15, 20
Reduce
To Average
Reduces to the mean average.
Returns undefined
if collection is empty.
function toAverage(
data: Iterable<number> | Iterator<number>,
): number | undefined
1import { reduce } from 'itertools-ts'; 2 3const grades = [100, 90, 95, 85, 94]; 4 5const finalGrade = reduce.toAverage(numbers); 6// 92.8
To Count
Reduces iterable to its length.
function toCount(data: Iterable<unknown>|Iterator<unknown>): number
1import { reduce } from 'itertools-ts'; 2 3const data = [1, 2, 3]; 4 5const length = reduce.toCount(data); 6// 3
To First
Reduces iterable to its first element.
function toFirst<T>(data: Iterable<T> | Iterator<T>): T
Throws LengthException
if collection is empty.
1import { reduce } from 'itertools-ts'; 2 3const medals = ['gold', 'silver', 'bronze']; 4 5const first = reduce.toFirst(medals); 6// gold
To First And Last
Reduces iterable to its first and last elements.
function toFirstAndLast<T>(data: Iterable<T> | Iterator<T>): [T, T]
Throws LengthException
if collection is empty.
1import { reduce } from 'itertools-ts'; 2 3const medals = ['gold', 'silver', 'bronze']; 4 5const result = reduce.toFirstAndLast(medals); 6// [gold, bronze]
To Last
Reduces iterable to its last element.
function toLast<T>(data: Iterable<T> | Iterator<T>): T
Throws LengthException
if collection is empty.
1import { reduce } from 'itertools-ts'; 2 3const medals = ['gold', 'silver', 'bronze']; 4 5const first = reduce.toFirst(medals); 6// bronze
To Max
Reduces to the max value.
function toMax<TValue>(
data: Iterable<TValue>|Iterator<TValue>,
compareBy?: (datum: TValue) => Comparable,
): TValue|undefined
- Optional callable param
compareBy
must return comparable value. - If
compareBy
is not provided then items of given collection must be comparable. - Returns
undefined
if collection is empty.
1import { reduce } from 'itertools-ts'; 2 3const numbers = [5, 3, 1, 2, 4]; 4 5const result = reduce.toMax(numbers); 6// 1 7 8const movieRatings = [ 9 { 10 title: 'The Matrix', 11 rating: 4.7, 12 }, 13 { 14 title: 'The Matrix Reloaded', 15 rating: 4.3, 16 }, 17 { 18 title: 'The Matrix Revolutions', 19 rating: 3.9, 20 }, 21 { 22 title: 'The Matrix Resurrections', 23 rating: 2.5, 24 }, 25]; 26const compareBy = (movie) => movie.rating; 27 28const lowestRatedMovie = reduce.toMin(movieRatings, compareBy); 29// { 30// title: 'The Matrix', 31// rating: 4.7, 32// }
To Min
Reduces to the min value.
function toMin<TValue>(
data: Iterable<TValue>|Iterator<TValue>,
compareBy?: (datum: TValue) => Comparable,
): TValue|undefined
- Optional callable param
compareBy
must return comparable value. - If
compareBy
is not provided then items of given collection must be comparable. - Returns
undefined
if collection is empty.
1import { reduce } from 'itertools-ts'; 2 3const numbers = [5, 3, 1, 2, 4]; 4 5const result = reduce.toMin(numbers); 6// 1 7 8const movieRatings = [ 9 { 10 title: 'The Matrix', 11 rating: 4.7, 12 }, 13 { 14 title: 'The Matrix Reloaded', 15 rating: 4.3, 16 }, 17 { 18 title: 'The Matrix Revolutions', 19 rating: 3.9, 20 }, 21 { 22 title: 'The Matrix Resurrections', 23 rating: 2.5, 24 }, 25]; 26const compareBy = (movie) => movie.rating; 27 28const lowestRatedMovie = reduce.toMin(movieRatings, compareBy); 29// { 30// title: 'The Matrix Resurrections', 31// rating: 2.5, 32// }
To Min Max
Reduces collection to its lower and upper bounds.
function toMinMax<T>(
data: Iterable<T> | Iterator<T>,
compareBy?: (item: T) => Comparable
): [T?, T?]
- Optional callable param
compareBy
must return comparable value. - If
compareBy
is not provided then items of given collection must be comparable. - Returns
[undefined, undefined]
if collection is empty.
1import { reduce } from 'itertools-ts'; 2 3const numbers = [5, 3, 1, 2, 4]; 4 5const result = reduce.toMinMax(numbers); 6// [1, 5] 7 8const movieRatings = [ 9 { 10 title: 'The Matrix', 11 rating: 4.7, 12 }, 13 { 14 title: 'The Matrix Reloaded', 15 rating: 4.3, 16 }, 17 { 18 title: 'The Matrix Revolutions', 19 rating: 3.9, 20 }, 21 { 22 title: 'The Matrix Resurrections', 23 rating: 2.5, 24 }, 25]; 26const compareBy = (movie) => movie.rating; 27 28const lowestRatedMovie = reduce.toMin(movieRatings, compareBy); 29// [{ 30// title: 'The Matrix Resurrections', 31// rating: 2.5, 32// }, 33// { 34// title: 'The Matrix', 35// rating: 4.7, 36// }]
To Product
Reduces to the product of its elements.
Returns undefined
if collection is empty.
function toProduct(data: Iterable<number>|Iterator<number>): number|undefined
1import { reduce } from 'itertools-ts'; 2 3const primeFactors = [5, 2, 2]; 4 5const number = reduce.toProduct(primeFactors); 6// 20
To Range
Reduces given collection to its range (difference between max and min).
function toRange(numbers: Iterable<Numeric> | Iterator<Numeric>): number
Returns 0
if iterable source is empty.
1import { reduce } from 'itertools-ts'; 2 3const grades = [100, 90, 80, 85, 95]; 4 5const range = reduce.toRange(numbers); 6// 20
To Sum
Reduces to the sum of its elements.
function toSum(data: Iterable<number>|Iterator<number>): number
1import { reduce } from 'itertools-ts'; 2 3const parts = [10, 20, 30]; 4 5const sum = reduce.toSum(parts); 6// 60
To Value
Reduce elements to a single value using reducer function.
function toValue<TInput, TOutput>(
data: Iterable<TInput> | Iterator<TInput>,
reducer: (carry: TOutput, datum: TInput) => TOutput,
initialValue?: TOutput
): TOutput
1import { reduce } from 'itertools-ts'; 2 3const input = [1, 2, 3, 4, 5]; 4const sum = (carry, item) => carry + item; 5 6const result = reduce.toValue(input, sum, 0); 7// 15
Set and multiset
Distinct
Filter out elements from the iterable only returning distinct elements.
function* distinct<T>(
data: Iterable<T>|Iterator<T>,
compareBy?: (datum: T) => Comparable
): Iterable<T>
Always treats different instances of objects and arrays as unequal.
1import { set } from 'itertools-ts'; 2 3const chessSet = ['rook', 'rook', 'knight', 'knight', 'bishop', 'bishop', 'king', 'queen', 'pawn', 'pawn']; 4 5for (const chessPiece of set.distinct(chessSet)) { 6 console.log(chessPiece); 7} 8// rook, knight, bishop, king, queen, pawn 9 10 11const users = [ 12 { 'name': 'John', 'id': 1 }, 13 { 'name': 'Mary', 'id': 2 }, 14 { 'name': 'Mary', 'id': 3 }, 15 { 'name': 'John', 'id': 4 }, 16 { 'name': 'Jane', 'id': 5 }, 17]; 18 19for (const user of set.distinct(users, (item) => item['name'])) { 20 console.log(user); 21} 22// { 'name': 'John', 'id': 1 }, { 'name': 'Mary', 'id': 2 }, { 'name': 'Jane', 'id': 5 }
Intersection
Iterates intersection of iterables.
function* intersection<T>(...iterables: Array<Iterable<T> | Iterator<T>>): Iterable<T>
- Always treats different instances of objects and arrays as unequal.
- If input iterables produce duplicate items, then multiset intersection rules apply.
1import { set } from 'itertools-ts'; 2 3const chessPieces = ['rook', 'knight', 'bishop', 'queen', 'king', 'pawn']; 4const shogiPieces = ['rook', 'knight', 'bishop', 'king', 'pawn', 'lance', 'gold general', 'silver general']; 5 6for (const commonPiece of set.intersection(chessPieces, shogiPieces)) { 7 console.log(commonPiece); 8} 9// rook, knight, bishop, king, pawn
Partial Intersection
Iterates M-partial intersection of iterables.
function* partialIntersection<T>(
minIntersectionCount: number,
...iterables: Array<Iterable<T> | Iterator<T>>
): Iterable<T>
- Always treats different instances of objects and arrays as unequal.
- If input iterables produce duplicate items, then multiset intersection rules apply.
1import { set } from 'itertools-ts'; 2 3const staticallyTyped = ['c++', 'java', 'c#', 'go', 'haskell']; 4const dynamicallyTyped = ['php', 'python', 'javascript', 'typescript']; 5const supportsInterfaces = ['php', 'java', 'c#', 'typescript']; 6 7for (const language of set.partialIntersection(2, staticallyTyped, dynamicallyTyped, supportsInterfaces)) { 8 console.log(language); 9} 10// c++, java, c#, go, php
Symmetric difference
Iterates the symmetric difference of iterables.
function* symmetricDifference<T>(
...iterables: Array<Iterable<T> | Iterator<T>>
): Iterable<T>
- Always treats different instances of objects and arrays as unequal.
- If input iterables produce duplicate items, then multiset difference rules apply.
1import { set } from 'itertools-ts'; 2 3const a = [2, 3, 4, 7]; 4const b = [2, 3, 5, 8]; 5const c = [2, 3, 6, 9]; 6 7for (const item of set.symmetricDifference(a, b, c)) { 8 console.log(item); 9} 10// 4, 5, 6, 7, 8, 9
Union
Iterates the union of iterables.
function* union<T>(...iterables: Array<Iterable<T> | Iterator<T>>): Iterable<T>
- Always treats different instances of objects and arrays as unequal.
- If input iterables produce duplicate items, then multiset difference rules apply.
1import { set } from 'itertools-ts'; 2 3const a = [1, 2, 3]; 4const b = [2, 3, 4]; 5const c = [3, 4, 5]; 6 7for (const item of set.symmetricDifference(a, b, c)) { 8 console.log(item); 9} 10// 1, 2, 3, 4, 5
Combinatorics
Cartesian Product
Iterates cartesian product of given iterables.
function* cartesianProduct<T extends Array<Iterable<unknown> | Iterator<unknown>>>(
...iterables: T
): Iterable<ZipTuple<T, never>>
1import { combinatorics } from 'itertools-ts'; 2 3const numbers = [1, 2]; 4const letters = ['a', 'b']; 5const chars = ['!', '?']; 6 7for (const tuple of combinatorics.cartesianProduct(numbers, letters, chars)) { 8 console.log(tuple); 9} 10/* 11 [1, 'a', '!'], 12 [1, 'a', '?'], 13 [1, 'b', '!'], 14 [1, 'b', '?'], 15 [2, 'a', '!'], 16 [2, 'a', '?'], 17 [2, 'b', '!'], 18 [2, 'b', '?'], 19*/
Combinations
Iterates all combinations of given iterable.
function* combinations<T>(
data: Iterable<T> | Iterator<T>,
length: number
): Iterable<Array<T>>
1import { combinatorics } from 'itertools-ts'; 2 3const fruits = ['apple', 'banana', 'cherry']; 4 5for (const combination of combinatorics.combinations(fruits, 2)) { 6 c
No vulnerabilities found.
No security vulnerabilities found.