-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
route-calculator.js
88 lines (69 loc) · 2.08 KB
/
route-calculator.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// '+' = add
// '-' = subtract
// '*' = multiply
// '$' = divide
// (division => multiplication => subtraction => addition)
const operations = {
'$': (a, b) => a / b,
'*': (a, b) => a * b,
'-': (a, b) => a - b,
'+': (a, b) => a + b,
};
function operate(parts, operator, fn) {
for (let i = 0; i < parts.length; i++) {
const token = parts[i];
if (token === operator) {
const result = fn(parts[i - 1], parts[i + 1]);
parts.splice(i - 1, 3, result);
i = i - 1;
}
}
}
function calculate(route) {
const parts = route
.split('')
.reduce(({ parts, currentNumber }, token, i, tokens) => {
if (operations[token]) {
parts = [...parts, +currentNumber, token];
currentNumber = '';
} else {
currentNumber += token;
}
if (i === tokens.length - 1) {
return [...parts, +currentNumber];
}
return { parts, currentNumber };
}, {
parts: [],
currentNumber: ''
});
Object
.keys(operations)
.forEach(operation => {
operate(parts, operation, operations[operation]);
});
return isNaN(parts[0]) ? '400: Bad request' : parts[0];
}
console.log(calculate('5*5*5'), 125);
console.log(calculate('1'), 1);
console.log(calculate('1.1'), 1.1);
console.log(calculate('1+1'), 2);
console.log(calculate('1-1'), 0);
console.log(calculate('2$2$2'), 1);
console.log(calculate('2*2'), 4);
console.log(calculate('1.1+1.9'), 3);
console.log(calculate('9$4'), 2.25);
console.log(calculate('1.5*3'), 4.5);
console.log(calculate('5-43.2'), -38.2);
console.log(calculate('5+5+5+5'), 20);
console.log(calculate('5-5-5-5'), -10);
console.log(calculate('5*5*5*5'), 625);
console.log(calculate('5$5$5$5'), 0.04);
console.log(calculate('1+1-1'), 1);
console.log(calculate('5*6$2+5-10'), 10);
console.log(calculate('1*1*1*1*1*1$1$1$1$1+1-1+9-1'), 9);
console.log(calculate('80 + 5 - 5 + 1'), 81);
console.log(calculate('5*6$2&5-10'), '400: Bad request');
console.log(calculate('5/10'), '400: Bad request');
console.log(calculate('p'), '400: Bad request');
console.log(calculate('9^9'), '400: Bad request');