|
| 1 | +/** |
| 2 | + * Evaluate a numeric operations string in postfix notation using a stack. |
| 3 | + * Supports basic arithmetic operations: +, -, *, / |
| 4 | + * @see https://www.geeksforgeeks.org/evaluation-of-postfix-expression/ |
| 5 | + * @param {string} expression - Numeric operations expression to evaluate. Must be a valid postfix expression. |
| 6 | + * @returns {number|null} - Result of the expression evaluation, or null if the expression is invalid. |
| 7 | + */ |
| 8 | +function evaluatePostfixExpression(expression) { |
| 9 | + const stack = []; |
| 10 | + |
| 11 | + // Helper function to perform an operation and push the result to the stack. Returns success. |
| 12 | + function performOperation(operator) { |
| 13 | + const rightOp = stack.pop(); // Right operand is the top of the stack |
| 14 | + const leftOp = stack.pop(); // Left operand is the next item on the stack |
| 15 | + |
| 16 | + if (leftOp === undefined || rightOp === undefined) { |
| 17 | + return false; // Invalid expression |
| 18 | + } |
| 19 | + switch (operator) { |
| 20 | + case '+': |
| 21 | + stack.push(leftOp + rightOp); |
| 22 | + break; |
| 23 | + case '-': |
| 24 | + stack.push(leftOp - rightOp); |
| 25 | + break; |
| 26 | + case '*': |
| 27 | + stack.push(leftOp * rightOp); |
| 28 | + break; |
| 29 | + case '/': |
| 30 | + if (rightOp === 0) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + stack.push(leftOp / rightOp); |
| 34 | + break; |
| 35 | + default: |
| 36 | + return false; // Unknown operator |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + const tokens = expression.split(/\s+/); |
| 42 | + |
| 43 | + for (const token of tokens) { |
| 44 | + if (!isNaN(parseFloat(token))) { |
| 45 | + // If the token is a number, push it to the stack |
| 46 | + stack.push(parseFloat(token)); |
| 47 | + } else { |
| 48 | + // If the token is an operator, perform the operation |
| 49 | + if (!performOperation(token)) { |
| 50 | + return null; // Invalid expression |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return (stack.length === 1) ? stack[0] : null; |
| 56 | +} |
| 57 | + |
| 58 | +export { evaluatePostfixExpression }; |
0 commit comments