Skip to content

Instantly share code, notes, and snippets.

@dagolinuxoid
Last active January 22, 2017 11:34
Show Gist options
  • Save dagolinuxoid/2826ae0ea73503f99e9e31d3fb8cee78 to your computer and use it in GitHub Desktop.
Save dagolinuxoid/2826ae0ea73503f99e9e31d3fb8cee78 to your computer and use it in GitHub Desktop.
https://learn.javascript.ru/constructor-new >> Задачи >> Создайте калькулятор | fun
---
version 1
---
//Oops... well, there probably was so much 'shame' that I decided to delete it :)
---
version 2
---
function Calculator() {
this.calculate = function (str) {
var x = +str.split(' ')[0];
var y = +str.split(' ')[2];
var operator = str.split(' ')[1];
if (operator === '+') return x + y;
if (operator === '-') return x - y;
return 'this feature isn\'t been implemented yet';
};
this.addMethod = function (name, funArg, str) {
var x = +str.split(' ')[0];
var y = +str.split(' ')[2];
var operator = str.split(' ')[1];
if (name === operator) return funArg(x,y); // day two; yet wrong
};
}
var calc = new Calculator;
calc.calculate('3 + 11');
calc.addMethod('*', (a,b) => a * b, '24 * 10');
---
version 3
---
function Calculator() {
this.container = {
'+': function(a,b) {
return a + b;
},
'-': (a,b) => a - b
};
this.calculate = function (str) {
var x = +str.split(' ')[0]; // Number(str.split(' ')[0]);
var y = +str.split(' ')[2];
var operator = str.split(' ')[1];
if (operator in this.container) { // this.container.hasOwnProperty(operator);
return this.container[operator](x,y);
}
return 'this functionality isn\'t supported... yet';
};
this.addMethod = function (name, funArg) {
this.container[name] = funArg;
return 'this feature is added :-) or has been already added earlier!';
};
}
var calc = new Calculator;
calc.calculate('3 + 11');
calc.addMethod('*',(a,b) => a * b);
calc.calculate('2 * 4');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment