how to get all combinations of a set in typescript

Here's an example TypeScript code that generates all possible combinations of a set of elements. It uses a recursive algorithm that generates all combinations of a set with n-1 elements, and then appends the nth element to each of these combinations.

index.ts
function getCombinations<T>(elements: T[]): T[][] {
  if (elements.length === 0) {
    return [[]];
  }

  const [first, ...rest] = elements;
  const combinationsWithoutFirst = getCombinations(rest);
  const combinationsWithFirst = combinationsWithoutFirst.map(
    (combination) => [first, ...combination]
  );

  return [...combinationsWithoutFirst, ...combinationsWithFirst];
}

// Example usage
const elements = [1, 2, 3];
const combinations = getCombinations(elements);
console.log(combinations); // Output: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
568 chars
19 lines

The getCombinations function takes an array of elements as input, and returns an array of arrays, where each inner array represents a unique combination of elements. The base case of the recursion is an empty array, which represents the set with zero elements, and has a single combination of zero elements.

The function then extracts the first element from the array, and generates all combinations of the remaining elements using the same function. It then appends the first element to each of these combinations, and returns the concatenation of the combinations with and without the first element.

gistlibby LogSnag