Skip to content

Instantly share code, notes, and snippets.

@gustavomorinaga
Created September 18, 2023 02:57
Show Gist options
  • Select an option

  • Save gustavomorinaga/0d8dc5e12ec1f1c3dea03d2d89903d04 to your computer and use it in GitHub Desktop.

Select an option

Save gustavomorinaga/0d8dc5e12ec1f1c3dea03d2d89903d04 to your computer and use it in GitHub Desktop.
Overridable Store for Svelte
import type { Updater, Writable } from 'svelte/store';
export type ChangeFn<T> = (args: { curr: T; next: T }) => T;
export const overridable = <T>(store: Writable<T>, onChange?: ChangeFn<T>) => {
const update = (updater: Updater<T>, sideEffect?: (newValue: T) => void) =>
store.update((curr) => {
const next = updater(curr);
let res: T = next;
if (onChange) res = onChange({ curr, next });
sideEffect?.(res);
return res;
});
const set: typeof store.set = (curr) => update(() => curr);
return { ...store, update, set };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment