WeakCounter
A weak map that counts occurrences of object keys.
Similar to Counter but uses WeakMap as the base, allowing garbage collection of keys.
@example
// Track reference counts for DOM elements
const elementRefs = new WeakCounter<HTMLElement>()
function addReference(element: HTMLElement) {
elementRefs.increment(element)
console.log(`References: ${elementRefs.get(element)}`)
}
function removeReference(element: HTMLElement) {
elementRefs.decrement(element)
console.log(`References: ${elementRefs.get(element)}`)
}
const div = document.createElement('div')
addReference(div) // References: 1
addReference(div) // References: 2
removeReference(div) // References: 1
@example
// Count object interactions without preventing garbage collection
const objectInteractions = new WeakCounter<object>()
function handleInteraction(obj: object, count = 1) {
objectInteractions.increment(obj, count)
}
const user = { id: 1, name: 'Alice' }
const session = { sessionId: 'abc123' }
handleInteraction(user, 3)
handleInteraction(session, 1)
handleInteraction(user, 2)
console.log(objectInteractions.get(user)) // 5
console.log(objectInteractions.get(session)) // 1
// When user and session are no longer referenced elsewhere,
// they can be garbage collected along with their counts
@example
// Initialize with existing counts
const cache1 = {}
const cache2 = {}
const cache3 = {}
const hitCounter = new WeakCounter<object>([
[cache1, 10],
[cache2, 5],
[cache3, 15]
])
hitCounter.increment(cache1, 3) // 10 -> 13
console.log(hitCounter.get(cache1)) // 13
console.log(hitCounter.get(cache2)) // 5
class WeakCounter<K extends WeakKey> extends WeakMap<K, number> {}
constructor(entries?: readonly (readonly [K, number])[] | null);
decrement(key: K, amount?: number): void;
get(key: K): number;
increment(key: K, amount?: number): void;