JSFiddle - React, Tailwind, and code Playground
JavaScript
function evaluatePostfix(str) {
const operationMap = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
};
const operations = Object.keys(operationMap);
const stack = [];
for (let i = 0; i < str.length; i++) {
const currentChar = str[i];
if (operations.indexOf(currentChar) > -1) {
const operand2 = stack.pop();
const operand1 = stack.pop();
const result = operationMap[currentChar](+operand1, +operand2);
stack.push(result);
} else {
stack.push(currentChar);
}
}
return stack[0];
}
/* Test run */
console.log(evaluatePostfix('12+'));
console.log(evaluatePostfix('56+7*'))