728x90
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
// } | |
// } |
'Algorithm > JavaScript(Node.js)' 카테고리의 다른 글
The Modern JS Tutorial: array-methods: map to objects (0) | 2021.09.20 |
---|---|
The Modern JS Tutorial: array-methods: map to names (0) | 2021.09.20 |
The Modern JS Tutorial: array-methods: filterRangeInPlace (0) | 2021.09.13 |
The Modern JS Tutorial: array-methods: filterRange (0) | 2021.09.13 |
The Modern JS Tutorial: array-methods: camelize (0) | 2021.09.13 |