Skip to content

Instantly share code, notes, and snippets.

@bigmistqke
Created January 29, 2025 15:22
Show Gist options
  • Save bigmistqke/4a10d81fa00a7e9e2e948e4ca72d178c to your computer and use it in GitHub Desktop.
Save bigmistqke/4a10d81fa00a7e9e2e948e4ca72d178c to your computer and use it in GitHub Desktop.
createReferenceCount: solid utility to map object to callback result and handle clean up with reference counting
const referenceCount = createReferenceCount();
function createReferenceCount() {
const map = new WeakMap<
object,
{ count: number; dispose: () => void; result: unknown }
>();
return function <T>(object: object, cb: () => T, debug?: string) {
try {
const node = map.get(object);
if (node) {
node.count++;
return node.result as T;
}
return createRoot((dispose) => {
const result = cb();
map.set(object, { dispose, count: 1, result });
return result;
});
} finally {
onCleanup(() => {
const node = map.get(object)!;
node.count--;
if (node.count === 0) {
node.dispose();
map.delete(object);
}
});
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment