-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcalc.js
More file actions
39 lines (38 loc) · 917 Bytes
/
calc.js
File metadata and controls
39 lines (38 loc) · 917 Bytes
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
function Calculator() {
let operators = [
['+', (a, b) => a + b],
['-', (a, b) => a - b],
];
this.calculate = function (str) {
let res
partStr = str.split(" ");
for (let key of operators) {
if (key[0] == partStr[1]) {
res = key[1]((+partStr[0]), (+partStr[2]));
}
}
return res;
}
this.addMethod = function (name, func) {
operators.push([name, func])
}
};
function Calculator() {
this.methods = {
"-": (a, b) => a - b,
"+": (a, b) => a + b
};
this.calculate = function(str) {
let split = str.split(' '),
a = +split[0],
op = split[1],
b = +split[2]
if (!this.methods[op] || isNaN(a) || isNaN(b)) {
return NaN;
}
return this.methods[op](a, b);
}
this.addMethod = function(name, func) {
this.methods[name] = func;
};
}