JSFiddle - React, Tailwind, and code Playground
by Torsten Walter
JavaScript
function calculate (expression) {
const parsedExpression = expression.split(" ");
const stack = new Stack();
let operandOne, operandTwo;
if (parsedExpression.length === 0) {
return 0;
}
parsedExpression.forEach((element) => {
if(isOperator(element)) {
operandTwo = parseInt(stack.pop());
operandOne = parseInt(stack.pop());
stack.push(mathOperations[element](operandOne, operandTwo));
} else {
stack.push(element);
}
});
return stack.pop();
}
class Stack {
constructor() {
this.values = [];
}
push(value) {
this.values.push(value);
}
pop() {
return this.values.pop();
}
}
const isOperator = (element) => {
return mathOperations.hasOwnProperty(element);
}
const mathOperations = {
"+": (operandOne, operandTwo) => operandOne + operandTwo,
"-": (operandOne, operandTwo) => operandOne - operandTwo,
"*": (operandOne, operandTwo) => operandOne * operandTwo,
"/": (operandOne, operandTwo) => operandOne / operandTwo
};