Skip to content

Instantly share code, notes, and snippets.

@sematgt
Created July 18, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sematgt/dedd87dc8e9918ce69951c3f4832c7cf to your computer and use it in GitHub Desktop.
Save sematgt/dedd87dc8e9918ce69951c3f4832c7cf to your computer and use it in GitHub Desktop.
Editable calculator on plain JS
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