All files / layers / L1 refCountStore.ts

96.42% Statements 54/56
92.85% Branches 26/28
100% Functions 14/14
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5763x 63x   140x 140x 71x 127x 99x 99x 17x 18x 7148x     18762x   243x 80x 80x 80x 471x     60x 60x 51x 51x 60x 60x 60x   49x 49x 60x 60x 48x 48x 4499x 4499x 4499x 4499x 4166x 4166x 2094x     129x 129x 129x 129x 125x 125x 92x        
type Key = string
type Listener = () => void
 
const counts = new Map<Key, number>()
const listeners = new Map<Key, Set<Listener>>()
 
function notify(key: Key): void {
  const set = listeners.get(key)
  if (set) {
    for (const listener of set) {
      listener()
    }
  }
}
 
export function refCountKey(entityPath: string, params: unknown): Key {
  return `${entityPath}:${JSON.stringify(params)}`
}
 
export function getRefCount(key: Key): number {
  return counts.get(key) ?? 0
}
 
export function incrementRefCount(key: Key): number {
 I const next = (counts.get(key) ?? 0) + 1
  counts.set(key, next)
  notify(key)
  return next
}
 
export fEunction decrementRefCount(key: Key): number {
  const current = counts.get(key)
  if (current === undefined) {
    return 0
  }
  const next = current - 1
  if (next === 0) {
    counts.delete(key)
  } else {
    counts.set(key, next)
  }
  notify(key)
  return next
}
 
export function subscribeRefCount(key: Key, listener: Listener): () => void {
  const set = listeners.get(key) ?? new Set()
  set.add(listener)
  listeners.set(key, set)
  return () => {
    set.delete(listener)
    if (set.size === 0) {
      listeners.delete(key)
    }
  }
}