Lazily computes the Cartesian product of multiple arrays or array-like objects.

The Cartesian product consists of all possible ordered combinations of the input arrays' elements whose type is infered automatically. This class implements the Iterable interface, allowing iteration with for...of and other iterable operations.

const arrays = [
[1, 2], // Array of numbers
['a', 'b'], // Array of strings
];

const product = new CartesianProduct(arrays);

// Get specific combination by index
console.log(product.get(0)); // [1, 'a']
console.log(product.get(1)); // [1, 'b']
console.log(product.get(2)); // [2, 'a']
console.log(product.get(3)); // [2, 'b']

// Iterate with for...of
for (const combination of product) {
console.log(combination); // [1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']
}

// Convert to array with Array.from()
const combinations = Array.from(product);
console.log(combinations); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

// Use iterator() directly
const iterator = product.iterator();
console.log(iterator.next().value); // [1, 'a']

Type Parameters

  • T extends InputArrays

    A tuple type representing an array of array-like objects.

Hierarchy (View Summary)

Implements

Constructors

Methods

  • Iterates over all combinations of the cartesian product and invokes the provided callback for each combination.

    Parameters

    • callback: (combination: CartesianProductTuple<T>, index: number) => void

      The function to be called for each combination, with the combination and its index as arguments.

    Returns void

  • Retrieves the combination (tuple) at a specific index in the Cartesian product.

    The index is computed based on the total number of possible combinations (the product of the sizes of the input arrays). If the provided index is outside the valid range (from 0 to total - 1), null is returned.

    Mathematical Calculation: The total number of combinations is calculated as the product of the lengths of all input arrays:

    total = size_1 * size_2 * ... * size_n
    

    Parameters

    • index: number

      The index of the combination to retrieve, between 0 and total - 1.

    Returns null | CartesianProductTuple<T>

    The combination at the specified index, or null if the index is out of bounds.