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;};}How the snippet works
Decorator Memoize With Cache Key keeps everything in the function memoize.
Using it
The primary signature is export function memoize(keyGen?:(...args:any[])
Import memoize from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `memoize` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.