To find the Cartesian product of 2 sets of strings and numbers in TypeScript, we can make use of arrays and generics.
Firstly, let us define the 2 sets that we want to find the Cartesian product of. We will create sets set1
and set2
, both with both string and numeric elements:
index.ts116 chars3 lines
Next, we define a function that takes in 2 sets as arguments and returns the Cartesian product of these sets.
index.ts223 chars10 lines
This function takes in 2 generic sets set1
and set2
. It creates an empty array of tuples that will hold the Cartesian product result. Then, it uses the forEach
method to iterate through both sets, appending each pair of elements to the result array.
We can now call this function using our set1
and set2
arguments to obtain the Cartesian product:
index.ts66 chars3 lines
The output of this code will be an array of tuples containing the Cartesian product of the two sets:
index.ts227 chars19 lines
gistlibby LogSnag