Created
July 18, 2020 08:43
-
-
Save sematgt/dedd87dc8e9918ce69951c3f4832c7cf to your computer and use it in GitHub Desktop.
Editable calculator on plain JS
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.operations = { | |
'+': (a, b) => +a + +b, | |
'-': (a, b) => a - b, | |
}; | |
this.validateInputNumbers = function(arr) { | |
return !(isNaN(arr[0]) || isNaN(arr[2])) | |
}; | |
this.validateInputOperator = function(arr) { | |
return Object.keys(this.operations).includes(arr[1]) | |
}; | |
this.calculate = function(str) { | |
let arr = str.split(' '); | |
if (!this.validateInputNumbers(arr)) { | |
return 'Inputted numbers are incorrect' | |
} | |
if (!this.validateInputOperator(arr)) { | |
return 'Inputted operator is unknown' | |
} | |
let operator = arr.splice(1, 1); | |
return arr.reduce(this.operations[operator]) | |
}; | |
this.addMethod = function(name, func) { | |
this.operations[name] = func; | |
} | |
} | |
let calc = new Calculator(); | |
console.log(calc.calculate('1 + 2')) | |
console.log(calc.calculate('2 + 2')) | |
console.log(calc.calculate('6 - 2')) | |
console.log(calc.calculate('6 - 10')) | |
console.log(calc.calculate('6s - 2')) | |
console.log(calc.calculate('6 - s2')) | |
console.log(calc.calculate('6- 2')) | |
console.log(calc.calculate('6 2')) | |
console.log(calc.calculate('6 -2')) | |
console.log(calc.calculate('lol12')) | |
console.log(calc.calculate('6 * 2')) | |
calc.addMethod("*", (a, b) => a * b); | |
console.log(calc.calculate('6 * 2')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment