how to get the cartesian product of two sets in typescript

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.ts
function cartesianProduct<T, U>(set1: T[], set2: U[]): [T, U][] {
  const result: [T, U][] = [];
  for (const item1 of set1) {
    for (const item2 of set2) {
      result.push([item1, item2]);
    }
  }
  return result;
}
223 chars
10 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.ts
const colors = ['red', 'blue', 'green'];
const sizes = ['small', 'medium', 'large'];

const combinations = cartesianProduct(colors, sizes);
console.log(combinations);
// Output: [ ['red', 'small'], ['red', 'medium'], ['red', 'large'], ['blue', 'small'], ['blue', 'medium'], ['blue', 'large'], ['green', 'small'], ['green', 'medium'], ['green', 'large'] ]
355 chars
7 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