Permutation with an ES6 JavaScript generator

As a follow up to my earlier entry on how to write a combination function in JavaScript, here is my function for permutations.

One thing I noticed while exploring the ES6 generator API is how useful for... of loops are. You can get by using while loops, as they are more or less just iterators, but it really helps makes the code more readable.

const permutations = function*(elements) {  
  if (elements.length === 1) {
    yield elements;
  } else {
    let [first, ...rest] = elements;
    for (let perm of permutations(rest)) {
      for (let i = 0; i < elements.length; i++) {
        let start = perm.slice(0, i);
        let rest = perm.slice(i);
        yield [...start, first, ...rest];
      }
    }
  }
}

See the JSFiddle for an example of how it is used.

Bret Lowrey

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

Florida, USA