const permute = (input = [], permutation = []) => {
if (input.length === 0) return [permutation]; // this will be one of the result
// choose each number in a loop
return input.reduce((allPermutations, current) => {
// reduce the input by removing the current element
// as we'll fix it by putting it in `permutation` array
const rest = input.filter(n => n != current);
return [
...allPermutations,
// fixing our choice in the 2nd arg
// by concatenationg current with permutation
...permute(rest, [...permutation, current])
];
}, []);
}