Created
January 18, 2024 05:36
-
-
Save PranavSK/c0d595334f33be5c83afa2579c7a8fa9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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