Passed
Push — master ( e4e4dd...8a294e )
by Nguyen
08:02 queued 02:04
created

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

Complexity

Total Complexity 8
Complexity/F 8

Size

Lines of Code 42
Function Count 1

Duplication

Duplicated Lines 23
Ratio 54.76 %

Importance

Changes 0
Metric Value
wmc 8
eloc 32
mnd 7
bc 7
fnc 1
dl 23
loc 42
bpm 7
cpm 8
noi 0
c 0
b 0
f 0
rs 10

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
const Stack = require('../index.js');
2
const operators = {
3
    "+": 1,
4
    "-": 1,
5
    "*": 2,
6
    "/": 2,
7
    "(": 3,
8
    ")": 3,
9
}
10
11
const infixToPrefix = (formula) => {
12
    let result = ""
13
    let stack = new Stack()
14 View Code Duplication
    for (let i = formula.length - 1; i >= 0; i--) {
15
        let c = formula[i]
16
        if (!operators[c]) {
17
            result += c
18
            continue
19
        }
20
        if (c === '(') {
21
            while (!stack.isEmpty() && stack.top() !== ')') {
22
                result += stack.pop()
23
            }
24
            stack.pop() // pop ')'
25
            continue
26
        }
27
        if (stack.isEmpty() || operators[c] >= operators[stack.top()] || stack.top() === ')') {
28
            stack.push(c)
29
            continue
30
        }
31
        while (!stack.isEmpty() && operators[stack.top()] > operators[c]) {
32
            let p = stack.pop()
33
                result += p
34
        }
35
        stack.push(c)
36
    }
37
    while (!stack.isEmpty()) {
38
        result += stack.pop()
39
    }
40
    return result.split('').reverse().join('')
41
}
42
module.exports = infixToPrefix
43