find the cartesian product of 2 sets of strings and numbers in typescript

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.ts
let set1: Set<string|number> = new Set(['a', 1, 'b', 2]);
let set2: Set<string|number> = new Set([3, 'c', 'd', 4]);
116 chars
3 lines

Next, we define a function that takes in 2 sets as arguments and returns the Cartesian product of these sets.

index.ts
function cartesianProduct<T, U>(set1: Set<T>, set2: Set<U>): Array<[T, U]> {
  let result = new Array<[T, U]>();
  set1.forEach((t) => {
    set2.forEach((u) => {
      result.push([t, u]);
    });
  });
  return result;
}
223 chars
10 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.ts
const result = cartesianProduct(set1, set2);
console.log(result);
66 chars
3 lines

The output of this code will be an array of tuples containing the Cartesian product of the two sets:

index.ts
[
  [ 'a', 3 ],
  [ 'a', 'c' ],
  [ 'a', 'd' ],
  [ 'a', 4 ],
  [ 1, 3 ],
  [ 1, 'c' ],
  [ 1, 'd' ],
  [ 1, 4 ],
  [ 'b', 3 ],
  [ 'b', 'c' ],
  [ 'b', 'd' ],
  [ 'b', 4 ],
  [ 2, 3 ],
  [ 2, 'c' ],
  [ 2, 'd' ],
  [ 2, 4 ]
]
227 chars
19 lines

gistlibby LogSnag