Exploring the concept of TypeScript function chaining and seeking a way to programmatically chain them together.
Check out this example class: chain.ts
class MyChain {
value: number = 0;
constructor() {
this.value = 0;
}
sum(args: number[]) {
this.value = args.reduce((s, c) => s + c, 0);
return this;
}
add(v: number) {
this.value = this.value + v;
return this;
}
subtract(v: number) {
this.value = this.value - v;
return this;
}
}
const mc = new MyChain();
console.log(mc.sum([1, 2, 3, 4]).subtract(5).value);
A console output of 5
is observed.
Attempting to understand how to programmatically chain these functions together led me to explore different approaches.
interface IChainObject {
action: string;
operand: number | number[];
}
const chainObj: IChainObject[] = [
{ action: "sum", operand: [1, 2, 3, 4] },
{ action: "subtract", operand: 5 },
];
One approach was to try:
// This doesn't work as intended
console.log(mc["sum"]([1, 2, 3, 4]).mc["subtract"](5).value);
This error was encountered: Property 'mc' does not exist on type 'MyChain'.ts(2339)
After some experimentation, a more successful method was discovered:
console.log(mc[chainObj[0].action](chainObj[0].operand)[chainObj[1].action](chainObj[1].operand).value);
Desiring an automated solution, the goal became to generate a dynamic chain from a predefined set of actions and operands:
const chainObj: IChainObject[] = [
{ action: "sum", operand: [1, 2, 3, 4] },
{ action: "subtract", operand: 5 },
];
While progress was made, confusion lingered regarding the inner workings of the code snippet:
myChain = mc[o.action](o.operand);
Despite achieving the desired result, further comprehension was sought to truly grasp the underlying logic of the operation.
The quest for enlightenment continues in unraveling the JavaScript magic behind chaining functions seamlessly within the context of programming.