Skip to content

Instantly share code, notes, and snippets.

@joshwashywash
Created August 25, 2023 17:05
Show Gist options
  • Save joshwashywash/9e159b7308c4e92feafc5b3827637447 to your computer and use it in GitHub Desktop.
Save joshwashywash/9e159b7308c4e92feafc5b3827637447 to your computer and use it in GitHub Desktop.
conditionally readable in svelte
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment