1function getArrayMutations(arr, perms = [], len = arr.length) {
2 if (len === 1) perms.push(arr.slice(0))
3
4 for (let i = 0; i < len; i++) {
5 getArrayMutations(arr, perms, len - 1)
6
7 len % 2 // parity dependent adjacent elements swap
8 ? [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]]
9 : [arr[i], arr[len - 1]] = [arr[len - 1], arr[i]]
10 }
11
12 return perms
13}
1const permutations = arr => {
2 if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
3 return arr.reduce(
4 (acc, item, i) =>
5 acc.concat(
6 permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
7 item,
8 ...val,
9 ])
10 ),
11 []
12 );
13};