Created
January 29, 2025 15:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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