ES6 JavaScript Combination Generator

One thing I find I need from time to time in any programming language are combinations and permutations of lists. Some languages like python include it in their standard library, but most of the time, I find it useful to keep an implementation handy I can reference.

Here is mine using the latest ES6 features, including generators. Having combinations in generators is useful when you only need a limited number of them. It can help improve performance quite a bit.

const combinations = function*(elements, length) {  
  for (let i = 0; i < elements.length; i++) {
    if (length === 1) {
      yield [elements[i]];
    } else {
      let remaining = combinations(elements.slice(i + 1, elements.length), length - 1);
      for (let next of remaining) {
        yield [elements[i], ...next];
      }
    }
  };
}

Checkout this JSFiddle to see it in action.

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA