how to get the power set of a set in typescript

To get the power set of a set in TypeScript, we can use the following function:

index.ts
function powerSet(set: Set<any>): Set<Set<any>> {
  const result = new Set([new Set()]);
  set.forEach((elem) => {
    result.forEach((subset) => {
      result.add(new Set([...subset, elem]));
    });
  });
  return result;
}
227 chars
10 lines

This function takes a set as input and returns a set of sets representing the power set. It works by iterating through each element in the input set and creating a new set that includes that element and every possible subset of the previously generated sets.

Here's an example of how we can use this function:

index.ts
const set = new Set([1, 2, 3]);
const powerSet = powerSet(set);
console.log(powerSet); // Output: Set { Set {}, Set { 1 }, Set { 2 }, Set { 3 }, Set { 1, 2 }, Set { 1, 3 }, Set { 2, 3 }, Set { 1, 2, 3 } }
205 chars
4 lines

In this example, we create a set containing the elements [1, 2, 3] and compute its power set using the powerSet() function. The resulting set is printed to the console, showing all the possible subsets of the input set.

gistlibby LogSnag