memoize
memoize() function
Creates a new function that, stores the results of its calculations in a Map. When the function is called with same input again, it retrieves the cached result instead of recalculating it. If resolver is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key
Signature:declare function memoize<F extends (...args: any[]) => any, K extends Parameters<F>[0], Return extends F & {
cache: K extends object ? WeakMap<K, ReturnType<F>> : Map<K, ReturnType<F>>;
}>(f: F): Return;
declare function memoize<F extends (...args: any[]) => any, Resolver extends (...args: Parameters<F>) => any, K extends ReturnType<Resolver>, Return extends F & {
cache: K extends object ? WeakMap<K, ReturnType<F>> : Map<K, ReturnType<F>>;
}>(f: F, resolver: Resolver): Return;
Example
const add10 = (a: number): number => a + 10;
const memoized = memoize(add10);
console.log(memoized(5)); // 15
console.log(memoized(10)) // 20
console.log(memoized(5)); // 15 (cached)
memoized.cache.clear(); // clear cache
console.log(memoized(5)); // 15 (no cache)