Skip to content

Instantly share code, notes, and snippets.

@PranavSK
Created January 18, 2024 05:36
Show Gist options
  • Save PranavSK/c0d595334f33be5c83afa2579c7a8fa9 to your computer and use it in GitHub Desktop.
Save PranavSK/c0d595334f33be5c83afa2579c7a8fa9 to your computer and use it in GitHub Desktop.
import type { Store } from 'nanostores'
import { onMount } from 'nanostores'
export function createStoreFactory<Id, StoreType extends Store<unknown>>(
initializer: (id: Id) => StoreType,
equal?: (a: Id, b: Id) => boolean
) {
const stores = new Map<Id, StoreType>()
const storeGetter = equal
? (id: Id) => {
for (const [key, store] of stores) {
if (equal(key, id)) return store
}
}
: (id: Id) => stores.get(id)
const factory = (id: Id) => {
let store = storeGetter(id)
if (store) return store
store = initializer(id)
stores.set(id, store)
onMount(store, () => {
// Remove the store if no subscribers. This is to prevent memory leaks.
return () => {
return factory.remove(id)
}
})
return store
}
factory.remove = equal
? (id: Id) => {
for (const [key] of stores) {
if (equal(key, id)) stores.delete(key)
}
}
: (id: Id) => stores.delete(id)
return factory
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment