Skip to content

Commit

Permalink
refactor: adjust memoize
Browse files Browse the repository at this point in the history
  • Loading branch information
Aarebecca committed Sep 19, 2024
1 parent 03941eb commit ccb2b7c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 14 deletions.
6 changes: 0 additions & 6 deletions __tests__/unit/lodash/memoize.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,9 @@ describe('memoize', () => {
expect(memoizedFn(1, 2)).toBe(3);
expect(memoizedFn(1, 2)).toBe(3);
expect(fn).toBeCalledTimes(1);
expect(memoizedFn.cache.size()).toEqual(1);
expect(memoizedFn.cache.has(1)).toBe(true);

expect(memoizedFn(2, 3)).toBe(5);
expect(memoizedFn(2, 3)).toBe(5);
expect(fn).toBeCalledTimes(2);

expect(memoizedFn.cache.size()).toEqual(1);
expect(memoizedFn.cache.has(1)).toBe(false);
expect(memoizedFn.cache.has(2)).toBe(true);
});
});
15 changes: 7 additions & 8 deletions src/lodash/memoize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ class FLRUCache<K, V> {
}
}

const CacheMap = new Map<Function, FLRUCache<any, any>>();

/**
* 缓存函数的计算结果,避免重复计算
* @example
Expand All @@ -58,21 +60,18 @@ class FLRUCache<K, V> {
* @param resolver 生成缓存 key 的函数
* @param maxSize lru 缓存的大小
*/
export default function memoize(fn: Function, resolver?: (...args: any[]) => string, maxSize = 128) {
export default function memoize<T extends Function>(fn: T, resolver?: (...args: any[]) => string, maxSize = 128) {
const memoized = function (...args) {
// 使用方法构造 key,如果不存在 resolver,则直接取第一个参数作为 key
const key = resolver ? resolver.apply(this, args) : args[0];
const cache = memoized.cache;
if (!CacheMap.has(fn)) CacheMap.set(fn, new FLRUCache(maxSize));
const cache = CacheMap.get(fn);

if (cache.has(key)) {
return cache.get(key);
}
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};

memoized.cache = new FLRUCache(maxSize);

return memoized;
return memoized as unknown as T;
}

0 comments on commit ccb2b7c

Please sign in to comment.