how to get all proper subsets of a set in javascript

index.tsx
function getSubsets(set) {
  const subsets = [[]];
  for (let elem of set) {
    for (let i = 0, len = subsets.length; i < len; ++i) {
      subsets.push(subsets[i].concat(elem));
    }
  }
  return subsets;
}
210 chars
10 lines

This code defines a function getSubsets that takes a set (represented as an array) as input and returns an array of all its proper subsets (i.e., all subsets except the original set itself and the empty set). The function uses a recursive algorithm to construct the subsets, starting with the empty set and adding one element at a time.

The outer loop iterates over each element in the input set. For each element, a new inner loop is started that iterates over every subset constructed so far. Each subset is cloned by concatenating the current element onto it, and the new subset is added to the list of subsets.

After all subsets have been constructed, the function returns the array of subsets. Note that the empty set is included in the list of subsets, but this is not considered a proper subset by definition.

gistlibby LogSnag