728x90
function Calculator() {
this.methods = {
'+': (a, b) => a + b,
'-': (a, b) => a - b
}
this.calculate = function(str) {
const split = str.split(' ');
const op = split[1];
const a = +split[0];
const b = +split[2];
console.log('err', this.methods[op]);
if(!this.methods[op] || isNaN(a) || isNaN(b)) {
return NaN;
}
return this.methods[op](a, b);
}
this.addMethod = function(op, fn) {
this.methods[op] = fn;
}
}
let powerCalc = new Calculator;
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);
let result = powerCalc.calculate("2 ** 3");
console.log( result ); // 8
// class
// class Calculator {
// constructor() {
// this.methods = {
// 'x': (a, b) => a + b,
// '-': (a, b) => a - b,
// }
// }
// calculate(str) {
// const arr = str.split(' ');
// const op = arr[1];
// const a = arr[0];
// const b = arr[2];
// return this.methods[op](a, b);
// }
// addMethod(op, fn) {
// this.methods[op] = fn;
// }
// }

+ Recent posts