Skip to content

Instantly share code, notes, and snippets.

@sdekna
Created August 19, 2023 08:26
Show Gist options
  • Save sdekna/beb66027a2b75af3b97942a7f2b99363 to your computer and use it in GitHub Desktop.
Save sdekna/beb66027a2b75af3b97942a7f2b99363 to your computer and use it in GitHub Desktop.
Alternate Svelte Store
// REPL: https://svelte.dev/repl/2c56758fb2ca4de9bf842e3dfb61ed36
function customStore<T>(initialValue: T, mutationFunction: (value: T)=>T, validationFunction: (value: T)=>boolean) {
let currentValue = initialValue
let previousValue: T | null = null;
const subscribers = new Set<(value: T, previousValue: T | null) => void>();
const set = (value: T): void => {
if (typeof window === 'undefined') return
if (mutationFunction) value = mutationFunction(value);
if (validationFunction && !validationFunction(value)) return console.log("validation statement failed... not updating the store")
previousValue = currentValue;
currentValue = value;
broadcastValue(currentValue, previousValue)
};
const subscribe = (callback: (value: T, previousValue: T | null) => void) => {
subscribers.add(callback);
callback(currentValue, previousValue);
return () => {
subscribers.delete(callback);
};
};
const update = (callback: (value: T, previousValue: T | null) => T): void => {
const newValue = callback(structuredClone(currentValue), previousValue);
set(newValue)
};
function broadcastValue(value: T, previousValue: T | null) {
subscribers.forEach((callback) => {
callback(value, previousValue);
});
}
function get(): T {
return currentValue
}
return {
subscribe,
update,
set,
get,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment