Skip to content

Instantly share code, notes, and snippets.

@arifhp86
Created October 13, 2016 23:36
Show Gist options
  • Save arifhp86/8b670360e14ddbfa4cc8de0d14c247a7 to your computer and use it in GitHub Desktop.
Save arifhp86/8b670360e14ddbfa4cc8de0d14c247a7 to your computer and use it in GitHub Desktop.
Fluent Calculator [js]
var Magic = function() {
var value = 0;
var operators = {
'plus': (a, b) => a + b,
'minus': (a, b) => a - b,
'times': (a, b) => a * b,
'dividedBy': (a, b) => a / b
};
var numbers = [
'zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten'
];
Object.keys(operators).forEach((operator) => {
var operatorFunction = operators[operator];
var operatorObject = {};
numbers.forEach((num, index) => {
Object.defineProperty(operatorObject, num, {
get: () => value = operatorFunction(value, index)
});
});
Number.prototype[operator] = operatorObject;
});
numbers.forEach((num, index) => {
Object.defineProperty(this, num, {
get: () => {
value = index;
return Number(index);
}
});
});
}
var FluentCalculator = new Magic();
console.log(FluentCalculator.two.plus.three); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment