I am trying to get this heaps algorithm to return an array of permutations instead of printing as below. I know it could be done by declaring an array outside of the function and pushing to it but, I want to avoid that approach. How can I make this return the array of permutations without using an outside array?
function heaps(arr, n) {
if (n === undefined) n = arr.length;
if (n <= 1) console.log(arr);
else {
for (let i = 0; i <= n - 1; i++)
{
heaps(arr, n-1);
if
(n % 2 === 0) [arr[n-1], arr[i]] = [arr[i], arr[n-1]];
else
[arr[n-1], arr[0]] = [arr[0], arr[n-1]];
}
}
}