memoize() function
创建一个新函数,将其计算结果存储在 Map 中。当使用相同输入再次调用该函数时,它检索缓存的结果而不是重新计算。如果提供了 resolver,它根据提供给记忆化函数的参数确定用于存储结果的缓存键。默认情况下,提供给记忆化函数的第一个参数用作 map 缓存键。
Signature:
typescript
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;Example
ts
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)