Skip to content

Instantly share code, notes, and snippets.

@frangio
Created June 4, 2022 00:50
Show Gist options
  • Save frangio/20e29b429a3a335ec560286675ac34bc to your computer and use it in GitHub Desktop.
Save frangio/20e29b429a3a335ec560286675ac34bc to your computer and use it in GitHub Desktop.
A helper to build custom Svelte stores
import type { Subscriber } from 'svelte/store';
export function store<T>(start: () => T, stop?: () => void) {
const subscribers = new Set<Subscriber<T>>();
let value: T;
function notify() {
for (const fn of subscribers) {
fn(value);
}
}
function set(newValue: T) {
const oldValue = value;
value = newValue;
if (!Object.is(newValue, oldValue)) {
notify();
}
}
function subscribe(fn: Subscriber<T>) {
if (subscribers.size === 0) {
value = start();
}
fn(value);
subscribers.add(fn);
return () => {
subscribers.delete(fn);
if (subscribers.size === 0) {
stop?.();
}
};
}
return {
subscribe,
notify,
set,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment