I’m trying to add operators into an array of numbers.
Just wondering if you have tips on solving this and if possible how I can conceptualise this effectively, because I’ve tried quite a bit and I’m still struggling. My current code is…
function insertOperators(charArray, numArray) {
let operatorRegex = /\+|\-|\//g
let operatorCount = 0;
let specialOperator;
for(let i = charArray.length - 1; i>0; i--) {
if (charArray[i].match(operatorRegex)
|| charArray[i] ==="*"
&& charArray[i-1] !=="*"
&& charArray[i+1] !=="*") {
/*
charArray = ["2", "-", "1", "+", "3"]
numArray = ["2", "1", "3"]
*/
specialOperator = charArray.slice(i, i+1);
console.log(specialOperator);
operatorCount--;
console.log(i);
console.log(operatorCount + i);
console.log(charArray[i], 'match at', i);
numArray.splice(operatorCount + i, 0, ...specialOperator);
console.log(operatorCount);
console.log(numArray);
}
// handle exponents
if (charArray[i] === "*"
&& charArray[i-1] === "*") {
console.log('still recorded');
specialOperator = charArray.slice(i-1, i+1);
joined = specialOperator.join('')
operatorCount--;
console.log(operatorCount);
let exponentPosition = i - 1;
numArray.splice(exponentPosition, 0, joined);
console.log('match at', i);
console.log(operatorCount);
console.log(numArray);
}
}
return numArray;
}
Tests
// insertOperators([“1”, “1”, “+”, “6”], [“11”, “6”]);
// insertOperators([“1”,“2”, “-”, “3”], [“12”, “3”]);
// insertOperators([“6”,“0”, “/”, “3”], [“60”, “3”]);
// insertOperators([“5”,“1”, “", “2”], [“51”, “2”]);
// insertOperators([“2”, “*”, “*”, “3”], [“2”, “3”])
// insertOperators([“2”, “*”, “*”, “3”, “+”, “5”], [“2”, “3”, “5”])
insertOperators([“2”, “-”, “1”, “+”, “3”],[“2”, “1”, “3”])
// insertOperators([“2”, "”, “*”, “3”, “+”, “5”, “-”, “2”], [“2”, “3”, “5”, “2”])