Skip to main content

cartesianProduct

Generates the cartesian product of two iterables.
a
Iterable<T>
required
The first iterable
b
Iterable<U>
required
The second iterable
return
[T, U][]
An array of tuples containing all possible pairs from the two iterables

Example

import { cartesianProduct } from "@temelj/iterator";

const colors = ["red", "blue"];
const sizes = ["S", "M", "L"];

const products = cartesianProduct(colors, sizes);
console.log(products);
// [
//   ["red", "S"],
//   ["red", "M"],
//   ["red", "L"],
//   ["blue", "S"],
//   ["blue", "M"],
//   ["blue", "L"]
// ]

permutations

Generates all permutations of the input iterable.
iterable
Iterable<T>
required
The iterable to permute
return
T[][]
An array of arrays, where each inner array is a unique permutation

Example

import { permutations } from "@temelj/iterator";

const items = [1, 2, 3];
const perms = permutations(items);

console.log(perms);
// [
//   [1, 2, 3],
//   [1, 3, 2],
//   [2, 1, 3],
//   [2, 3, 1],
//   [3, 1, 2],
//   [3, 2, 1]
// ]

combinations

Generates all combinations of a specific size from the input iterable.
iterable
Iterable<T>
required
The iterable to generate combinations from
n
number
required
The size of each combination
return
T[][]
An array of arrays, where each inner array is a unique combination of size n
throws
Error
Throws an error if n is negative

Example

import { combinations } from "@temelj/iterator";

const items = [1, 2, 3, 4];
const combs = combinations(items, 2);

console.log(combs);
// [
//   [1, 2],
//   [1, 3],
//   [1, 4],
//   [2, 3],
//   [2, 4],
//   [3, 4]
// ]

// Empty result when n is larger than the array
console.log(combinations([1, 2], 3)); // []

// Single empty array when n is 0
console.log(combinations([1, 2, 3], 0)); // [[]]

Build docs developers (and LLMs) love