en.javascript.info/1-js/4-object-basics/07-constructor-new/4-calculator-extendable/_js.view/solution.js
Ilya Kantor 3defacc09d up
2016-11-12 19:38:58 +03:00

29 lines
468 B
JavaScript

function Calculator() {
var methods = {
"-": function(a, b) {
return a - b;
},
"+": function(a, b) {
return a + b;
}
};
this.calculate = function(str) {
var split = str.split(' '),
a = +split[0],
op = split[1],
b = +split[2]
if (!methods[op] || isNaN(a) || isNaN(b)) {
return NaN;
}
return methods[op](a, b);
}
this.addMethod = function(name, func) {
methods[name] = func;
};
}