either
import { either } from 'patronum';// orimport { either } from 'patronum/either';Motivation
The method select one or other value based on condition.
You can think about it as a ternary operator a ? b : c.
Formulae
$result = either($filter, then, other);$resultstore contains value ofthenif$filterstore containstrue$resultstore contains value ofotherif$filterstore containsfalse
Arguments
$filter: Store<boolean>— The store contains condition how to select betweenthenandotherthen: Store<Then> | Then— First value can be a Store, and returned when$filteristrueother: Store<Other> | Other— Second value can be a Store too, returned only when$filteriffalse
Then— Generic type argument. Required only to distinguish this type fromOtherOther— Generic type argument used for the alternative value when$filterisfalse
Returns
$result: Store<Then | Other>— Store contains one of the value depends on$filtervalue
Object form arguments
For some cases it is useful to add names for each argument.
$result = either({ filter, then, other,});Types, descriptions, and usage the same as for positional arguments.
Example
const $showLatest = createStore(false);const $latestTweets = createStore<Tweet[]>([]);const $recommendedTweets = createStore<Tweet[]>([]);
export const $tweets = either($showLatest, $latestTweets, $recommendedTweets);Select just one argument
Sometimes we want to write an inverted expression, like this imperative code:
if (!active) { return another;}return null;We can write exactly null as is:
const $result = either($active, null, $another); // Store<null | Another>We may want to use not for condition:
import { either, not } from 'patronum';
const $result = either(not($active), $another, null);Alternative
import { createStore, combine } from 'effector';const $showLatest = createStore(false);const $latestTweets = createStore<Tweet[]>([]);const $recommendedTweets = createStore<Tweet[]>([]);
export const $tweets = combine( $showLatest, $latestTweets, $recommendedTweets, (showLatest, latestTweets, recommendedTweets) => showLatest ? latestTweets : recommendedTweets,);