forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluateExpression.js
More file actions
Latest commit
58 lines (52 loc) · 1.74 KB
/
Copy pathEvaluateExpression.js
File metadata and controls
58 lines (52 loc) · 1.74 KB
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.
*/
functionevaluatePostfixExpression(expression){
conststack=[]
// Helper function to perform an operation and push the result to the stack. Returns success.
functionperformOperation(operator){
constrightOp=stack.pop()// Right operand is the top of the stack
constleftOp=stack.pop()// Left operand is the next item on the stack
if(leftOp===undefined||rightOp===undefined){
returnfalse// 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){
returnfalse
}
stack.push(leftOp/rightOp)
break
default:
returnfalse// Unknown operator
}
returntrue
}
consttokens=expression.split(/\s+/)
for(consttokenoftokens){
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)){
returnnull// Invalid expression
}
}
}
returnstack.length===1 ? stack[0] : null
}
export{evaluatePostfixExpression}