refcount.ts 641 B

1234567891011121314151617181920212223242526
  1. import { onCleanup } from "solid-js"
  2. export function createRefCountMap<T>(create: (key: string) => T) {
  3. const items = new Map<string, T>()
  4. const refCounts = new Map<string, number>()
  5. return (key: string) => {
  6. onCleanup(() => {
  7. refCounts.set(key, (refCounts.get(key) ?? 0) - 1)
  8. if (refCounts.get(key) === 0) {
  9. items.delete(key)
  10. refCounts.delete(key)
  11. }
  12. })
  13. const cached = items.get(key)
  14. if (cached) {
  15. refCounts.set(key, (refCounts.get(key) ?? 0) + 1)
  16. return cached
  17. }
  18. const item = create(key)
  19. items.set(key, item)
  20. refCounts.set(key, 1)
  21. return item
  22. }
  23. }