I am writing code of calculator considering the priority of operation. What I am trying to do is to replace the priority that matches the regular expression I wrote and calculate it, and loop through it until the length of string, which is the input initially, becomes 1.
The below is my code, but running it results in an infinite loop.
const Calculator = function() {
this.evaluate = string => {
let regex = /\((\d+)\s[*/+-]\s(\d+)\)|(\d+)\s[*/]\s(\d+)|(\d+)\s[+-]\s(\d+)/g
while(string.length > 1) {
string.replace(regex, cal);
}
return string;
}
};
function cal(argument) {
let temp = argument.split(' ');
let regexP = /\((\d+)|(\d+)\)/g
if(temp[0].match(regexP)) {
temp[0] = temp[0].slice(1);
temp[2] = temp[2].slice(0, 1);
}
switch(temp[1]) {
case '+': return +temp[0] + +temp[2];
case '-': return +temp[0] - +temp[2];
case '*': return +temp[0] * +temp[2];
case '/': return +temp[0] / +temp[2];
default: return undefined;
}
}
let calculate = new Calculator()
console.log(calculate.evaluate("2 / 2 + 3 * 4 - 6"));
For some reason, the code is looping over and over and isn't returning a value.
What am I doing wrong, and how can I fix it?