memoize

Cache function results to avoid redundant computations.

#async #performance #cache #utility
export const memoize = <A extends string | number, R>(
fn: (arg: A) => R,
) => {
const cache = new Map<A, R>();
return (arg: A): R => {
if (cache.has(arg)) return cache.get(arg)!;
const res = fn(arg);
cache.set(arg, res);
return res;
};
};
// Usage
const expensiveCalc = memoize((n: number) => {
console.log('Computing...');
return n * n;
});
expensiveCalc(5); // Computing... 25
expensiveCalc(5); // 25 (cached)

Share this snippet

Comments