| Total Complexity | 9 |
| Complexity/F | 9 |
| Lines of Code | 46 |
| Function Count | 1 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | const Stack = require('../index.js'); |
||
| 2 | const operators = { |
||
| 3 | "+": 1, |
||
| 4 | "-": 1, |
||
| 5 | "*": 2, |
||
| 6 | "/": 2, |
||
| 7 | "(": 3, |
||
| 8 | ")": 4, |
||
| 9 | } |
||
| 10 | const infixToPostFix = (formula) => { |
||
| 11 | let result = "" |
||
| 12 | let stack = new Stack() |
||
| 13 | for (let i = 0; i < formula.length; i++) { |
||
| 14 | let c = formula[i] |
||
| 15 | if (!operators[c]) { |
||
| 16 | result += c |
||
| 17 | continue |
||
| 18 | } |
||
| 19 | if (c == '(') { |
||
| 20 | stack.push(c) |
||
| 21 | continue |
||
| 22 | } |
||
| 23 | if (c == ')') { |
||
| 24 | while (stack.top() != '(') { |
||
| 25 | c = stack.pop() |
||
| 26 | result += c |
||
| 27 | } |
||
| 28 | stack.pop() // pop '(' |
||
| 29 | continue |
||
| 30 | } |
||
| 31 | let top = stack.top() |
||
| 32 | if (stack.isEmpty() || top == '(' || operators[c] > operators[top]) { |
||
| 33 | stack.push(c) |
||
| 34 | } else { |
||
| 35 | while (!stack.isEmpty() && operators[top] >= operators[c]) { |
||
| 36 | result += stack.pop() |
||
| 37 | } |
||
| 38 | stack.push(c) |
||
| 39 | } |
||
| 40 | } |
||
| 41 | while (!stack.isEmpty()) { |
||
| 42 | result += stack.pop() |
||
| 43 | } |
||
| 44 | return result |
||
| 45 | } |
||
| 46 | module.exports = infixToPostFix |
||
| 47 |