JSFiddle - React, Tailwind, and code Playground
by Torsten Walter
JavaScript
function isOperator(token) {
return token === '-' || token === '+' || token === '*' || token === '/';
}
function evaluate(operand1, operator, operand2) {
switch (operator) {
case '-':
return operand1 - operand2;
case '+':
return operand1 + operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
}
}
function calculate (expression) {
if (expression === '')
return 0;
const tokens = expression.split(' ');
const operands = [];
tokens.forEach((token) => {
if(isOperator(token)) {
const operand2 = operands.pop();
const operand1 = operands.pop();
console.log(operand1, token, operand2)
const result = evaluate(operand1, token, operand2);
operands.push(result);
} else {
operands.push(Number(token));
}
})
return operands.pop();
}
document.getElementById('out').innerHTML = calculate('1 3 +')