feat: add algorithm to evaluate postfix string (#1441)

* feat: add algorithm to evaluate postfix strings

* feat: add test case for evaluate expression

* update: add literature reference

* fix: import name in testcase

* fix: test case result

* Make clear that this is postfix

* Update tests

* add: see reference

* fixes mentioned issues

* Fix `default` case

---------

Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
Gaurav Giri
2023-10-10 12:45:59 +05:45
committed by GitHub
parent 05750bce43
commit 52858f8a09
2 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,58 @@
/**
* Evaluate a numeric operations string in postfix notation using a stack.
* Supports basic arithmetic operations: +, -, *, /
* @see https://www.geeksforgeeks.org/evaluation-of-postfix-expression/
* @param {string} expression - Numeric operations expression to evaluate. Must be a valid postfix expression.
* @returns {number|null} - Result of the expression evaluation, or null if the expression is invalid.
*/
function evaluatePostfixExpression(expression) {
const stack = [];
// Helper function to perform an operation and push the result to the stack. Returns success.
function performOperation(operator) {
const rightOp = stack.pop(); // Right operand is the top of the stack
const leftOp = stack.pop(); // Left operand is the next item on the stack
if (leftOp === undefined || rightOp === undefined) {
return false; // Invalid expression
}
switch (operator) {
case '+':
stack.push(leftOp + rightOp);
break;
case '-':
stack.push(leftOp - rightOp);
break;
case '*':
stack.push(leftOp * rightOp);
break;
case '/':
if (rightOp === 0) {
return false;
}
stack.push(leftOp / rightOp);
break;
default:
return false; // Unknown operator
}
return true;
}
const tokens = expression.split(/\s+/);
for (const token of tokens) {
if (!isNaN(parseFloat(token))) {
// If the token is a number, push it to the stack
stack.push(parseFloat(token));
} else {
// If the token is an operator, perform the operation
if (!performOperation(token)) {
return null; // Invalid expression
}
}
}
return (stack.length === 1) ? stack[0] : null;
}
export { evaluatePostfixExpression };

View File

@ -0,0 +1,22 @@
import { evaluatePostfixExpression } from '../EvaluateExpression.js';
describe('evaluatePostfixExpression', () => {
it('should evaluate a valid expression', () => {
const expression = '3 4 * 2 / 5 +'; // (3 * 4) / 2 + 5 = 11
const result = evaluatePostfixExpression(expression);
expect(result).toBe(11);
});
it('should handle division by zero', () => {
const expression = '3 0 /'; // Division by zero
const result = evaluatePostfixExpression(expression);
expect(result).toBe(null);
});
it('should handle an invalid expression', () => {
const expression = '3 * 4 2 / +'; // Invalid expression
const result = evaluatePostfixExpression(expression);
expect(result).toBe(null);
});
});