Created
October 1, 2020 22:02
-
-
Save Gerst20051/a891cab3a459c39482ae4d956e69f2b4 to your computer and use it in GitHub Desktop.
Simple Calculator Class
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
class Calculator { | |
#numbers = { | |
'zero': 0, | |
'one': 1, | |
'two': 2, | |
'three': 3, | |
'four': 4, | |
'five': 5, | |
'six': 6, | |
'seven': 7, | |
'eight': 8, | |
'nine': 9, | |
}; | |
#operators = { | |
'plus': '+', | |
'minus': '-', | |
'multiply': '*', | |
'divide': '/', | |
'modulus': '%', | |
'exp': '**', | |
}; | |
#calculation = []; | |
constructor() { | |
this.__createNumberMethods(); | |
this.__createOperatorMethods(); | |
} | |
__createNumberMethods() { | |
Object.keys(this.#numbers).forEach(numberKey => { | |
this[numberKey] = function() { | |
this.#calculation.push(this.#numbers[numberKey]); | |
return this; | |
}; | |
}); | |
} | |
__createOperatorMethods() { | |
Object.keys(this.#operators).forEach(operatorKey => { | |
this[operatorKey] = function() { | |
this.#calculation.push(this.#operators[operatorKey]); | |
return this; | |
}; | |
}); | |
} | |
clearCalculation() { | |
this.#calculation = []; | |
} | |
getCalculation() { | |
return this.#calculation.join(''); | |
} | |
equals() { | |
const calculation = this.getCalculation(); | |
this.clearCalculation(); | |
return eval(calculation); | |
} | |
} | |
const calculator = new Calculator(); | |
console.log(calculator.equals() === undefined); | |
console.log(calculator.one().equals() === 1); | |
console.log(calculator.one().zero().zero().equals() === 100); | |
console.log(calculator.one().plus().two().equals() === 3); | |
console.log(calculator.one().minus().two().equals() === -1); | |
console.log(calculator.two().multiply().two().equals() === 4); | |
console.log(calculator.one().two().divide().three().equals() === 4); | |
console.log(calculator.one().two().modulus().three().equals() === 0); | |
console.log(calculator.two().exp().three().equals() === 8); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment