Skip to content

Instantly share code, notes, and snippets.

@amiika
Created August 17, 2023 12:19
Show Gist options
  • Save amiika/743bfa6a275e4bedcf8171007e33d1b3 to your computer and use it in GitHub Desktop.
Save amiika/743bfa6a275e4bedcf8171007e33d1b3 to your computer and use it in GitHub Desktop.
Typescript method chaining example with the automatic evaluation at the end
export class Method {
originalValue: string;
value: string;
constructor(value: string) {
this.originalValue = value;
this.value = value;
}
add(value: string): Method {
this.value += value;
return this;
}
reverse(): Method {
this.value = this.value.split("").reverse().join("");
return this;
}
reset(): void {
this.value = this.originalValue;
}
}
export class Chain {
private link: Method;
private evaluated: boolean = false;
constructor(value: string) {
this.link = new Method(value);
}
next(): Method {
if (!this.evaluated) this.evaluated = true;
return this.link;
}
sometimesBy(chance: number, func: Function) {
if(Math.random() < chance) {
func();
}
return this;
}
getResult(): string {
return this.link.value;
}
reset(value: string): void {
this.link.reset();
}
isEvaluated(): boolean {
return this.evaluated;
}
}
const chainCache = new Map<string, Chain>();
const getCachedChain = (values: string): Chain => {
const key = values;
const cachedChain = chainCache.get(key);
if (cachedChain) return cachedChain;
const newChain = new Chain(values);
chainCache.set(key, newChain);
return newChain;
}
const modString = (values: string): Method => {
const chain = getCachedChain(values);
if (chain.isEvaluated()) {
console.log("Result:", chain.getResult());
chain.reset(values);
} else {
console.log("Method chain is starting...");
}
return chain.next();
}
let i = 0;
while (i++ <= 10) {
modString("foo").add("a").add("b").reverse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment