function Calc() {
let state = {};
let digits = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
for (let i = 0, l = digits.length; i < l; i++) {
Object.defineProperty(this, digits[i], {
get: function() {
if (!state.o) {
state.v = i;
return this;
}
if (state.o === 'plus') state.v = state.v + i;
if (state.o === 'minus') state.v = state.v - i;
if (state.o === 'times') state.v = state.v * i;
if (state.o === 'divide') state.v = state.v / i;
return this;
}
});
}
let operations = ['plus', 'minus', 'times', 'divide'];
for (let i = 0, l = operations.length; i < l; i++) {
Object.defineProperty(this, operations[i], {
get: function() {
state.o = operations[i];
return this;
}
});
}
this.value = function() {
let {v} = state;
state = {};
return v;
};
}
let calc = new Calc();
console.log(calc.one.plus.two.value()); // 3
console.log(calc.one.minus.four.value()); // -3
console.log(calc.one.plus.one.minus.two.value()); // 0
console.log(calc.one.value()); // 1