Hex Core JS
    Preparing search index...

    Function cartesianProduct

    Computes the cartesian product of a given collection of arrays. based on (but slightly faster than) https://github.com/ehmicky/fast-cartesian without any caching

    This function works by generating a string and then using the Function constructor to define a function from that string. This makes the generated function extremely efficient, both in time and memory. The generated code is also very easy to read, since it is effectively how a programmer would implement this by hand if they had a fixed number of arrays.

    The generated code looks like

    let count = 0;
    const n0 = 2;
    const n1 = 3;
    for (let i0 = 0; i0 < n0; i0++) {
    for (let i1 = 0; i1 < n1; i1++) {
    result[count] = [arrays[0][i0], arrays[1][i1]];
    count++;
    }
    }

    arrays to take the product of, in order

    • Computes the cartesian product of a given pair of arrays

      Type Parameters

      • A
      • B

      Parameters

      • a: A[]

        the first array

      • b: B[]

        the second array

      Returns [A, B][]

    • Computes the cartesian product of three arrays

      Type Parameters

      • A
      • B
      • C

      Parameters

      • a: A[]

        the first array

      • b: B[]

        the second array

      • c: C[]

        the third array

      Returns [A, B, C][]

    • Computes the cartesian product of four arrays

      Type Parameters

      • A
      • B
      • C
      • D

      Parameters

      • a: A[]

        the first array

      • b: B[]

        the second array

      • c: C[]

        the third array

      • d: D[]

        the fourth array

      Returns [A, B, C, D][]

    • Computes the cartesian product of five arrays

      Type Parameters

      • A
      • B
      • C
      • D
      • E

      Parameters

      • a: A[]

        the first array

      • b: B[]

        the second array

      • c: C[]

        the third array

      • d: D[]

        the fourth array

      • e: E[]

        the fifth array

      Returns [A, B, C, D, E][]