Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support nested memoize #4

Merged
merged 2 commits into from
Oct 30, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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