GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — JavaScript/Data-Structures/Stack/EvaluateExpression.js at master · TheAlgorithms/JavaScript

Expand file tree

/

EvaluateExpression.js

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
58 lines (52 loc) · 1.74 KB
/

EvaluateExpression.js

Copy path

File metadata and controls

58 lines (52 loc) · 1.74 KB
Raw
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 }
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.