Decorator Memoize With Cache Key
Memoize method results via a decorator with configurable cache key generation for expensive computations.
Code
const caches=new WeakMap<object,Map<string,unknown>>();export function memoize(keyGen?:(...args:any[])=>string){return function(target:any,propertyKey:string,descriptor:PropertyDescriptor){const original=descriptor.value;descriptor.value=function(...args:any[]){let cache=caches.get(this);if(!cache){cache=new Map();caches.set(this,cache);}const key=keyGen?keyGen(...args):JSON.stringify(args);if(cache.has(key))return cache.get(key);const result=original.apply(this,args);cache.set(key,result);return result;};return descriptor;};}Report a problem with this exampleOpens a pre-filled issue on GitHub.