Performs the same basic functionality as unwrapOrElse
, but instead
of simply unwrapping the value if it is Ok
and applying a value to
generate the same default type if it is Err
, lets you supply
functions which may transform the wrapped type if it is Ok
or get a default
value for Err
.
This is kind of like a poor man's version of pattern matching, which JavaScript currently lacks.
Instead of code like this:
import Result, { isOk, match } from 'true-myth/result';
const logValue = (mightBeANumber: Result<number, string>) => {
console.log(
mightBeANumber.isOk
? mightBeANumber.value.toString()
: `There was an error: ${unsafelyGetErr(mightBeANumber)}`
);
};
...we can write code like this:
import Result, { match } from 'true-myth/result';
const logValue = (mightBeANumber: Result<number, string>) => {
const value = match(
{
Ok: n => n.toString(),
Err: e => `There was an error: ${e}`,
},
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 isOk
and applying a value to generate the same default type if it isErr
, lets you supply functions which may transform the wrapped type if it isOk
or get a default value forErr
.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.