Here is the simple example I did
// ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
// If operator pop two numbers
// If number add it into stack
// 4 -> Add to stack
// 13 -> Add to stack
// 5 -> Add to stack
// / -> 13 -> a and 5 -> b (13 / 5) -> add to stack
// + -> 4 + (13 / 5)
const reverseTo = ["4", "13", "5", "/", "+"];
var stack = [];
var operators = ["+", "-", "/" , "*"];
function operation(a,b, operator){
switch(operator){
case '+':
return a+b;
case '/':
return a/b;
case '*':
return a*b;
case '-':
return a-b;
}
}
reverseTo.map(item => {
if(operators.includes(item)){
b = stack.pop();
a = stack.pop();
var output = operation(parseInt(a),parseInt(b),item);
// console.log(b,a,output, item)
stack.push(output);
}else{
stack.push(item);
}
});
console.log(stack);