Method Chaining 1
Included both implementation using Function as Constructor and Object.
function Calculator() {
this.total = 0;
this.add = (num) => {
this.total += num;
return this;
};
this.subtract = (num) => {
this.total -= num;
return this;
};
this.divide = (num) => {
this.total /= num;
return this;
};
this.multiply = (num) => {
this.total *= num;
return this;
};
}
const calculator1 = new Calculator();
calculator1.add(10).subtract(2).divide(2).multiply(5);
console.log(calculator1.total); // 20
const calculator2 = {
total: 0,
add(num) {
this.total += num;
return this;
},
subtract(num) {
this.total -= num;
return this;
},
divide(num) {
this.total /= num;
return this;
},
multiply(num) {
this.total *= num;
return this;
},
};
calculator2.add(10).subtract(2).divide(2).multiply(5);
console.log(calculator2.total); // 20
Method Chaining 2
Implementation using Function as Closure
function ComputeAmount() {
let total = 0;
function crore(num) {
total += num * Math.pow(10, 7);
return this;
}
function lacs(num) {
total += num * Math.pow(10, 5);
return this;
}
function thousand(num) {
total += num * Math.pow(10, 3);
return this;
}
function value() {
return total;
}
return {
crore,
lacs,
thousand,
value,
};
}
const amount1 = ComputeAmount().lacs(9).lacs(1).thousand(10).value();
console.log(amount1, amount1 === 1010000); // 1010000 true
const amount2 = ComputeAmount()
.lacs(15)
.crore(5)
.crore(2)
.lacs(20)
.thousand(45)
.crore(7)
.value();
console.log(amount2, amount2 === 143545000); // 143545000 true