In the code below, the operatorSequence function should run using the variable "input" and not "inputArray", however the inputArray ("a") is altered when the function is run.
What is causing this issue, and how can it be fixed so that the inputArray isn't changed?
//factorial in maths
function factorial(input) {
if (input == 0) return 1;
if (input > 0) return input * factorial(input - 1);
}
//slices an index from an array
function sliceIndex(array, index) {
let temp = array.slice(0, index);
temp.push.apply(temp, array.slice(index + 1));
return temp;
}
//operator sequence
function operatorSequence(inputArray, operatorArray, det) {
//the function should run on the "input" variable
let input = inputArray;
//det determines bracket position
//according to the bracket position, two input indices are merged into one, and an operator is deleted
while(operatorArray.length > 0) {
let temp1 = factorial(operatorArray.length - 1);
let temp2 = Math.floor(det / temp1);
input[temp2] = operatorArray[temp2](input[temp2], input[temp2 + 1]);
operatorArray = sliceIndex(operatorArray, temp2);
input = sliceIndex(input, temp2 + 1);
det -= temp1 * temp2;
}
return input[0];
}
const a = [1, 8, 3, 4];
let b = [(a, b) => a + b, (a, b) => a - b, (a, b) => a * b];
console.log(operatorSequence(a, b, 0));
console.log(a);
//24
//[9, 8, 3, 4]