-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.js
55 lines (48 loc) · 1.7 KB
/
calc.js
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
function calc (data) {
data = data.replace(/\s/g, '')
data = data.split('')
let numbers = []
let fSign = false
let fNumStarted = false
let fParenthesis = 0
data.forEach(element => {
if (!fParenthesis) {
if (element.match(/[0-9]/)) {
if (fNumStarted) {
numbers[numbers.length - 1] = numbers[numbers.length - 1] + element
}
else {
if (fSign) numbers.push(fSign + element)
else numbers.push(element)
fNumStarted = true
}
}
if (element.match(/\+/)) {
fSign = '+'
fNumStarted = false
}
if (element.match(/-/)) {
fSign = '-'
fNumStarted = false
}
if (element.match(/\(/)) {
fParenthesis++
numbers.push([])
}
} else {
if (element.match(/\)/)) {
fParenthesis--
if (!fParenthesis) numbers[numbers.length - 1] = fSign ? Number(fSign + '1') * calc(numbers[numbers.length - 1]) : calc(numbers[numbers.length - 1])
else numbers[numbers.length - 1] = numbers[numbers.length - 1] + element
fSign = false
} else if (element.match(/\(/)) {
numbers[numbers.length - 1] = numbers[numbers.length - 1] + element
fParenthesis++
} else {
numbers[numbers.length - 1] = numbers[numbers.length - 1] + element
}
}
});
return numbers.reduce((acc, x) => acc + Number(x), 0)
}
module.exports = calc