Passed
Push — master ( 06adb3...07a6a5 )
by Nguyen
41s queued 15s
created

topics/stack/infix-to-postfix/index.js   A

Complexity

Total Complexity 9
Complexity/F 9

Size

Lines of Code 46
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 36
mnd 8
bc 8
fnc 1
dl 0
loc 46
bpm 8
cpm 9
noi 0
c 0
b 0
f 0
rs 10
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