( create: (key: string) => T, remove?: (key: string) => void, identity: (key: string) => string = (key) => key, )
| 1 | import { onCleanup } from "solid-js" |
| 2 | |
| 3 | export function createRefCountMap<T>( |
| 4 | create: (key: string) => T, |
| 5 | remove?: (key: string) => void, |
| 6 | identity: (key: string) => string = (key) => key, |
| 7 | ) { |
| 8 | const items = new Map<string, T>() |
| 9 | const refCounts = new Map<string, number>() |
| 10 | |
| 11 | return (key: string) => { |
| 12 | const id = identity(key) |
| 13 | onCleanup(() => { |
| 14 | refCounts.set(id, (refCounts.get(id) ?? 0) - 1) |
| 15 | if (refCounts.get(id) === 0) { |
| 16 | remove?.(id) |
| 17 | items.delete(id) |
| 18 | refCounts.delete(id) |
| 19 | } |
| 20 | }) |
| 21 | |
| 22 | const cached = items.get(id) |
| 23 | if (cached) { |
| 24 | refCounts.set(id, (refCounts.get(id) ?? 0) + 1) |
| 25 | return cached |
| 26 | } |
| 27 | const item = create(key) |
| 28 | items.set(id, item) |
| 29 | refCounts.set(id, 1) |
| 30 | return item |
| 31 | } |
| 32 | } |
no test coverage detected