how to get the power set of a set in javascript

Here's a simple JavaScript function to find the power set of a set using recursion:

index.tsx
function powerSet(set) {
  // If the set is empty, return the empty set
  if (set.length === 0) {
    return [[]];
  }

  // Get the first element of the set
  const [first, ...rest] = set;

  // Find the power set of the remaining elements
  const powerSetOfRest = powerSet(rest);

  // Add the first element to each set in the power set of the remaining elements
  const withFirst = powerSetOfRest.map((subset) => [first, ...subset]);

  // Return the combined set of the power set of the remaining elements and the new sets with the first element added
  return powerSetOfRest.concat(withFirst);
}
601 chars
19 lines

The function takes an array set and returns an array of arrays, representing the power set of the original set.

For example:

index.tsx
console.log(powerSet([1, 2, 3])); // prints [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
94 chars
2 lines

gistlibby LogSnag