I need to execute an expression according to Order of Operations, and I can't figure out how to resolve the side-by-side brackets.
I am receiving an expression as a string -> "(add (multiply 4 5) (add 13 1))"
I can't figure out how to resolve this side by side case.
How I have it working for a case where everything is nested by grabbing the innermost brackets and then solving the next like this:
// Find innermost equasion
const findInnerEq = (str) =>
str.substring(str.lastIndexOf("(") + 1, str.lastIndexOf(")"));
// Find Brackets RegEx
const brakets = /(?<=\().*(?=\))/g;
// Changing RegEx function
const changeRE = (str) =>
str.slice(str.lastIndexOf("(") + 1, str.indexOf(")"));
// Return calculation
const calculate = (str) => {
let exp = findInnerEq(str).toLowerCase().split(" ");
let calc = exp
.slice(1)
.map((element) => parseInt(element))
switch (exp[0]) {
case "add":
if (calc.length > 2){
return calc.reduce((acc, cur) => acc + cur, 0);
}
return calc[0] + calc[1]
break;
case "multiply":
return calc.reduce((acc, cur) => acc * cur, 1);
break;
default:
console.log("Please enter valid expression");
process.exit();
}
};
// Recursive function
const calculator = (str) => {
let curString;
if (str.match(brakets)) {
curString = str;
let changingReg = `\(${changeRE(curString)}\)`;
curString = curString.replace(changingReg, calculate(curString));
return calculator(curString);
} else {
return str;
}
};
console.log(calculator("(add 2 (multiply 2 2))"));
console.log(calculator("(add (multiply 2 2) (add 2 2)"));
How can I deal with the side-by-side brackets?
Well, it looks like a classic problem from CS, and you are approaching it wrong.
What you should do instead, is use stacks, pushing items to them until you meet ')', which will tell you to execute the action on the stack collected so far.
Here is one of explanations https://orkhanhuseyn.medium.com/what-are-stack-based-calculators-cf2dbe249264
try this:
let arr = str.split("(").join("|:|:|:|").split(")").join("|:|:|:|").split("|:|:|:|")
//arr is now an array that has been split at both ( and )
// the middle value: arr[arr.length/2]
//evaluate it, and then combine it with arr[arr.length/2+1] and arr[arr.length/2-1]
//continue the cycle until your whole expression is evaluated