import { derived } from 'svelte/store';
import type { Readable } from 'svelte/store';
export const conditionally =
(readable: Readable<boolean>) =>
<T>(whenTrue: T, whenFalse: T): Readable<T> =>
derived(readable, ($readable): T => {
return $readable ? whenTrue : whenFalse;
});
usage:
<script>
import { writable } from 'svelte/store';
const w = writable(true);
const c = conditionally(w)('it is true', 'it is false');
console.log($c) // 'it is true';
w.set(false)
console.log($c) // 'it is false';
</script>
conditionally
's return function is generic so you can type it if needed.- you can pass anything into the function returned from
conditionally
even functions as long as the types of whenTrue and whenFalse are compatible
<script>
const whenTrue = () => console.log('it is true');
const whenFalse = () => {};
const c2 = conditionally(w)(whenTrue)(whenFalse);
// then you can call c2 and it will be the true branch when `w` is true and the false branch otherwise
</script>