Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active Jul 22, 2020
Embed
What would you like to do?
Svelte's Store implementation
function noop () {}
export function writable (init, start) {
let subscribers = [];
let prev = init;
let running = false;
let stop;
function notify () {
let subs = subscribers.concat();
let value = prev;
for (let subscriber of subs) {
try {
subscriber(value);
} catch {}
}
}
function set (curr) {
if (!running) return;
if (curr !== prev) {
prev = curr;
if (stop) notify();
}
}
function update (updater) {
set(updater(prev));
}
function subscribe (listener) {
subscribers.push(listener);
if (subscribers.length === 1) {
running = true;
prev = init;
let ret = start(set);
notify();
stop = typeof ret === 'function' ? ret : noop;
}
return function unsubscribe () {
let index = subscribers.findIndex((subscriber) => (
subscriber === listener
));
subscribers.splice(index, 1);
if (subscribers.length === 0) {
running = false;
try {
stop();
} catch {}
}
}
}
return { update, set, subscribe };
}
export function readable (init, fn) {
return {
subscribe: writable(init, fn).subscribe,
};
}
export function derived (store, fn, init) {
return readable(init, (set) => {
return store.subscribe((value) => {
set(fn(value));
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment