Similar to chain (in other languages called bind
or >>=
), but supports more functions passed at once (resembles do
notation in Haskell).
It is used to model a sequence of operations where each operation can fail (can return None).
// does addition when first argument is number
const f1 =
(x: string | number) => (y: number) => opt(x).narrow(isNumber).map(z => z + y);
// passes only even numbers
const f2 = (x: number): Opt<number> => x % 2 === 0 ? opt(x) : none;
opt(0).act( // Some(0)
f1(-2), // Some(-2)
f2, // Some(-2)
optNegative, // None
); // None
opt(0).act( // Some(0)
f1(1), // Some(1)
f2, // None
optNegative, // won't get called, still None
); // None
opt(3).act( // Some(3)
f1(1), // Some(4)
f2, // Some(4)
optNegative, // Some(4)
); // Some(4)
Similar to act, but functions return empty values instead of Opt.
It is useful for typical JavaScript functions (e.g. lodash), properly handles undefined
/null
/NaN
at any point of the chain.
const data = [{}, {f: true, a: [{b: 7, c: 1}]}, {a: [{}]}];
opt(data).actToOpt(
find(x => Boolean(x?.f)), // {f: true, a: [{b: 7, c: 1}]}
x => x?.a, // [{b: 7, c: 1}]
find(x => x.b === 8) // undefined
); // None
Alias of act
Alias of actToOpt.
Similar to map, but supports more functions which are called in succession, each on a result of a previous one.
const sq = (x: number) => x * x;
const dec = (x: number) => x - 1;
opt(4).mapFlow(sq, dec) // Some(15)
opt(null).mapFlow(sq, dec) // None
Applies passed function to this instance and returns function result.
Also known as a reverse function application, |>
(Reason/ReScript, F#, OCaml), &
(Haskell), #
(PureScript) or a pipe operator.
some(1).pipe(x => x.isEmpty) // false
none.pipe(x => x.isEmpty) // true
Supports multiple functions.
opt(1).pipe( // Some(1)
x => x.isEmpty, // false
x => !x, // true
) // true
some(1).chainToOpt(x => x === 1 ? null : x + 1) // None
some(2).chainToOpt(x => x === 1 ? null : x + 1) // Some(3)
Get a first item of an array.
Get a last item of an array.
Widen union (typically union of strings to string). Experimental. May be removed if it is later found out it's unsafe and unfixable.
opt(someValueOfUnionType).widen<SuperOfThatUnion>() // :Opt<SuperOfThatUnion>
Create Opt instance from an array of one or zero items.
Opt.fromArray([]) // None
Opt.fromArray([1]) // Some(1)
Generated using TypeDoc
Opt with a value inside.
Opt