simontonsoftware / s-libs

A collection of libraries for any of javascript, rxjs, or angular.
MIT License
43 stars 5 forks source link

[js-core] Feature request: `getCombinations()` #84

Closed ersimont closed 1 year ago

ersimont commented 2 years ago

It could be nice to have fancy tuple return types for low length values, too.

export function getCombinations<T>(elements: T[], length: number): T[][] {
  if (elements.length < length) {
    return [];
  }

  const results: T[][] = [];
  const result: T[] = [];
  result.length = length;
  combine(length, 0);
  return results;

  function combine(len: number, start: number): void {
    if (len === 0) {
      results.push(result.slice());
      return;
    }
    for (let i = start; i <= elements.length - len; i++) {
      result[result.length - len] = elements[i];
      combine(len - 1, i + 1);
    }
  }
}