refactor(app): extract refcount utility and clean up server sdk context (#29155)
This commit is contained in:
parent
03bb53c389
commit
9495ecd536
5 changed files with 266 additions and 280 deletions
26
packages/app/src/utils/refcount.ts
Normal file
26
packages/app/src/utils/refcount.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { onCleanup } from "solid-js"
|
||||
|
||||
export function createRefCountMap<T>(create: (key: string) => T) {
|
||||
const items = new Map<string, T>()
|
||||
const refCounts = new Map<string, number>()
|
||||
|
||||
return (key: string) => {
|
||||
onCleanup(() => {
|
||||
refCounts.set(key, (refCounts.get(key) ?? 0) - 1)
|
||||
if (refCounts.get(key) === 0) {
|
||||
items.delete(key)
|
||||
refCounts.delete(key)
|
||||
}
|
||||
})
|
||||
|
||||
const cached = items.get(key)
|
||||
if (cached) {
|
||||
refCounts.set(key, (refCounts.get(key) ?? 0) + 1)
|
||||
return cached
|
||||
}
|
||||
const item = create(key)
|
||||
items.set(key, item)
|
||||
refCounts.set(key, 1)
|
||||
return item
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue