how to get all subsets of a set in typescript

Here's a function in TypeScript that takes a set as input and returns an array of all its subsets:

index.ts
function getAllSubsets(set: Set<any>): any[][] {
  const subsets = [];
  const setArray = Array.from(set);

  // Calculate 2^n (the number of all possible subsets)
  const max = 1 << setArray.length;

  // Loop through all possible subsets
  for (let i = 0; i < max; i++) {
    const subset = [];

    // Convert the subset index to binary
    let j = i;
    let index = 0;
    while (j > 0) {
      if ((j & 1) === 1) {
        subset.push(setArray[index]);
      }
      j >>= 1;
      index++;
    }

    subsets.push(subset);
  }

  return subsets;
}
555 chars
28 lines

The function works by first converting the input set into an array, then using a loop to calculate all possible subsets (2^n where n is the size of the input set). Each subset is represented by a binary number where a value of 1 indicates that the corresponding element is included and a value of 0 indicates that it is not.

The loop converts each subset index to binary and adds the elements corresponding to the set bits to the current subset. The resulting subset is then added to a final array of subsets that is returned at the end.

gistlibby LogSnag