Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
58 lines (52 loc) · 1.74 KB

File metadata and controls

58 lines (52 loc) · 1.74 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.