I wrote an implementation of Heap's permutation algorithm in JavaScript (ES2015):
const swap = (array, pos1, pos2) => {
const temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
}
const heapsPermute = (() => {
const result = [];
return (array, n = array.length) => {
const newArray = typeof array === 'string'
? array.split('')
: array;
if (n === 1)
result.push(newArray.join(''));
for (let i = 1; i <= n; i++) {
heapsPermute(newArray, n - 1);
const j = n % 2
? 0
: i - 1;
swap(newArray, j, n - 1);
}
return result;
};
})();
console.log(heapsPermute('abcdef').length);
It should take an array|string argument and return array of strings with all permutations.
What do you think about it. Is there room for improvement anywhere?