-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathBasic Calculator.js
77 lines (59 loc) · 1.65 KB
/
Basic 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
var calculate = function(s) {
const numStack = [[]];
const opStack = [];
const isNumber = char => !isNaN(char);
function calculate(a, b, op){
if(op === '+') return a + b;
if(op === '-') return a - b;
}
let number = '';
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (char === ' ') continue;
if (isNumber(char)) {
number += char;
continue;
}
if(number) { // i.e. char is not a number so the number has ended
if (numStack[numStack.length - 1].length === 0) {
numStack[numStack.length - 1].push(+number);
} else {
const a = numStack[numStack.length - 1].pop();
const op = opStack.pop();
numStack[numStack.length - 1].push(calculate(a, +number, op));
}
number = '';
}
if (char === '(') {
if (numStack[numStack.length - 1].length === 0) {
numStack[numStack.length - 1].push(0);
opStack.push('+');
}
numStack.push([]); // Start a new stack for this parenthesis
continue;
}
if (char === ')') {
const b = numStack.pop().pop();
const a = numStack[numStack.length - 1].pop();
const op = opStack.pop();
numStack[numStack.length - 1].push(calculate(a, b, op));
continue;
}
if (char === '+' || char === '-') {
if (numStack[numStack.length - 1].length === 0) {
numStack[numStack.length - 1].push(0);
}
opStack.push(char);
continue;
}
// We should never reach here
throw new Error('Unexpected input: ' + char);
}
if(number){
if (numStack[numStack.length - 1].length === 0) return +number;
const a = numStack[numStack.length - 1].pop();
const op = opStack.pop();
numStack[0].push(calculate(a, +number, op));
}
return numStack.pop().pop();
};