To get the cartesian product of two sets in TypeScript, you can use nested loops and tuples. Here's an example function that takes in two arrays as arguments and returns their cartesian product as a new array of tuples:
index.ts223 chars10 lines
In this example, the function cartesianProduct
takes in two arrays set1
and set2
of types T
and U
respectively. It initializes an empty array result
to store the cartesian product.
The function then goes through each item in set1
and couples it with each item in set2
using nested loops. The resulting tuples [item1, item2]
are then pushed into the result
array.
Finally, the function returns the result
array containing all possible combinations of items from set1
and set2
.
Here's an example usage of the cartesianProduct
function:
index.ts355 chars7 lines
In this example, the cartesianProduct
function is used to get all possible combinations of colors and sizes, resulting in a new array of tuples.
gistlibby LogSnag