-
Hi, I'm trying out this formulation of export function atomFamily<K, V extends object>(
create: (key: K) => V,
): (key: K) => V {
let cache = new Map<K, WeakRef<V>>();
let registry = new FinalizationRegistry<K>((key) => {
cache.delete(key);
});
return (key) => {
let value = cache.get(key)?.deref();
if (value === undefined) {
value = create(key);
registry.register(value, key);
let weakRef = new WeakRef(value);
cache.set(key, weakRef);
}
return value;
};
} What do you guys think? Any flaws on this approach? |
Beta Was this translation helpful? Give feedback.
Answered by
dmaskasky
Oct 17, 2024
Replies: 1 comment 1 reply
-
This would totally work and I actually wrote this code before. But it has a huge problem. What if an atom gets dereferenced too early? Then the next time you call |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
jvliwanag
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This would totally work and I actually wrote this code before.
But it has a huge problem. What if an atom gets dereferenced too early? Then the next time you call
fooFamily(3)
, you will get a new atom and the previous state would be lost.