Skip to content

Instantly share code, notes, and snippets.

@intrnl
Created Jul 22, 2020
Embed
What would you like to do?
Basic readable and derived stores
export function readable (init, start) {
function subscribe (listener) {
let running = true;
let prev = init;
let stop;
function set (curr) {
if (running && curr !== prev) {
prev = curr;
if (stop) listener(curr);
}
}
stop = start(set) || noop
listener(prev);
return function unsubscribe () {
running = false;
stop();
}
}
return { 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