Performs the same basic functionality as unwrapOrElse
, but instead
of simply unwrapping the value if it is Just
and applying a value
to generate the same default type if it is Nothing
, lets you
supply functions which may transform the wrapped type if it is Just
or get a
default value for Nothing
.
This is kind of like a poor man's version of pattern matching, which JavaScript currently lacks.
Instead of code like this:
import Maybe from 'true-myth/maybe';
const logValue = (mightBeANumber: Maybe<number>) => {
const valueToLog = Maybe.mightBeANumber.isJust
? mightBeANumber.value.toString()
: 'Nothing to log.';
console.log(valueToLog);
};
...we can write code like this:
import { match } from 'true-myth/maybe';
const logValue = (mightBeANumber: Maybe<number>) => {
const value = match(
{
Just: n => n.toString(),
Nothing: () => 'Nothing to log.',
},
mightBeANumber
);
console.log(value);
};
This is slightly longer to write, but clearer: the more complex the resulting expression, the hairer it is to understand the ternary. Thus, this is especially convenient for times when there is a complex result, e.g. when rendering part of a React component inline in JSX/TSX.
Performs the same basic functionality as
unwrapOrElse
, but instead of simply unwrapping the value if it isJust
and applying a value to generate the same default type if it isNothing
, lets you supply functions which may transform the wrapped type if it isJust
or get a default value forNothing
.This is kind of like a poor man's version of pattern matching, which JavaScript currently lacks.
Instead of code like this:
...we can write code like this:
This is slightly longer to write, but clearer: the more complex the resulting expression, the hairer it is to understand the ternary. Thus, this is especially convenient for times when there is a complex result, e.g. when rendering part of a React component inline in JSX/TSX.