I'm using the Heap's Algorithm and it's working well with the callback function output
console logging the outcomes. But if I change the action of the callback function output
to array.push
, it pushes the same array over and over. What am I doing wrong?
let swap = function (array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
};
let permutationHeap = function (array, callback, n) {
n = n || array.length;
if (n === 1) {
callback(array);
} else {
for (var i = 1; i <= n; i++) {
permutationHeap(array, callback, n - 1);
if (n % 2) {
swap(array, 0, n - 1);
} else {
swap(array, i - 1, n - 1);
}
}
}
};
let finalResult = [];
var output = function (input) {
//console.log(input);
finalResult.push(input);
};
permutationHeap(["Mary", "John", "Denis"], output);
console.log(finalResult)
An array is an
Object
, objects are pointers/references.. I used thespread
operator to kinda clone the input so it doesnt keep doing the reference jitsu