Skip to content

Commit

Permalink
support nested memoize (#4)
Browse files Browse the repository at this point in the history
* support nested memoize

* use deep untracked object as cache key
  • Loading branch information
dai-shi committed Oct 30, 2020
1 parent f1c20a0 commit 4751f8e
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
createDeepProxy,
isDeepChanged,
getUntrackedObject,
trackMemo,
} from 'proxy-compare';

const untrack = <T>(x: T, seen: Set<T>): T => {
Expand All @@ -18,6 +19,12 @@ const untrack = <T>(x: T, seen: Set<T>): T => {
return x;
};

const getDeepUntrackedObject = <Obj extends object>(obj: Obj): Obj => {
const untrackedObj = getUntrackedObject(obj);
if (untrackedObj === null) return obj;
return getDeepUntrackedObject(untrackedObj);
};

// properties
const OBJ_PROPERTY = 'o';
const RESULT_PROPERTY = 'r';
Expand All @@ -44,14 +51,16 @@ const memoize = <Obj extends object, Result>(
const resultCache = new WeakMap<Obj, Result>();
const proxyCache = new WeakMap();
const memoizedFn = (obj: Obj) => {
if (resultCache.has(obj)) return resultCache.get(obj) as Result;
const cacheKey = getDeepUntrackedObject(obj);
if (resultCache.has(cacheKey)) return resultCache.get(cacheKey) as Result;
for (let i = 0; i < memoList.length; i += 1) {
const memo = memoList[i];
if (!isDeepChanged(memo[OBJ_PROPERTY], obj, memo[AFFECTED_PROPERTY], proxyCache)) {
resultCache.set(obj, memo[RESULT_PROPERTY]);
resultCache.set(cacheKey, memo[RESULT_PROPERTY]);
return memo[RESULT_PROPERTY];
}
}
trackMemo(obj);
const affected = new WeakMap<object, unknown>();
const proxy = createDeepProxy(obj, affected, proxyCache);
const result = untrack(fn(proxy), new Set());
Expand All @@ -61,7 +70,7 @@ const memoize = <Obj extends object, Result>(
[AFFECTED_PROPERTY]: affected,
});
if (memoList.length > size) memoList.pop();
resultCache.set(obj, result);
resultCache.set(cacheKey, result);
return result;
};
return memoizedFn;
Expand Down

0 comments on commit 4751f8e

Please sign in to comment.