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);
$result
store contains value ofthen
if$filter
store containstrue
$result
store contains value ofother
if$filter
store containsfalse
Arguments
$filter: Store<boolean>
— The store contains condition how to select betweenthen
andother
then: Store<Then> | Then
— First value can be a Store, and returned when$filter
istrue
other: Store<Other> | Other
— Second value can be a Store too, returned only when$filter
iffalse
Then
— Generic type argument. Required only to distinguish this type fromOther
Other
— Generic type argument used for the alternative value when$filter
isfalse
Returns
$result: Store<Then | Other>
— Store contains one of the value depends on$filter
value
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,);