Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created May 25, 2021 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fostyfost/bdb6b0c06fe41e6648337bf4903f602c to your computer and use it in GitHub Desktop.
Save fostyfost/bdb6b0c06fe41e6648337bf4903f602c to your computer and use it in GitHub Desktop.
Get string ref counter
export interface RefCounter<T = unknown> {
getCount(item: T): number
add(item: T): void
remove(item: T): void
}
export const getStringRefCounter = (): RefCounter<string> => {
const values: Record<string, number | undefined> = {}
const getCount = (key: string): number => values[key] || 0
return {
getCount,
add(key: string): void {
values[key] = getCount(key) + 1
},
remove(key: string): void {
const count = getCount(key)
if (count) {
if (count === 1) {
delete values[key]
} else {
values[key] = count - 1
}
}
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment