forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvaluateExpression.js
58 lines (52 loc) · 1.74 KB
/
EvaluateExpression.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 }