value-maybe
This library provides facilities for managing optionals - situations where a value may be absent. Meaning:
- There is a value, and it equals
x
.
or
- There isn’t a value at all
In JS optionals (null
and undefined
) are ubiquitous and there for flow type checker takes a creative approach (thas is very similar to Swift's) at defining maybe type (as found in many functional languages) for handling optionals.
This library take's flow's definition of "Maybe" type and provides implementations for set APIs typically available for values of maybe type.
Definition
just
/ nothing
You can think of optional values as just(x)
or nothing()
and that is why library exports just
& nothing
functions. Their existence is purely symbolic and serves nothing else but to communicate optional type of the value:
Maybe // => 5Maybe // => null
P.S: Obviously you could have used 5
and null
(or undefined
) instead.
isJust
/ isNothing
Maybe // => falseMaybe // => falseMaybe // => true Maybe // => trueMaybe // => trueMaybe // => false
withDefault
withDefault
can be used to cast optional value
into a guaranteed value by providing a default in case value
is absent.
Maybe // => 42Maybe // => 100
map
map
can be used to apply a function to optional value
if it is available one. If value
is Nothing
, it will just propagate through:
Maybe // => nullMaybe // => nullMaybe // => 6Maybe // => 'HELLO'
oneOf
oneOf
maybe used to pick the first maybe that actually has a value
. Useful when you want to try a couple different things, but there is no default value:
Maybe // => 42Maybe // => 71Maybe // => null
chain
chain
can be used to chain together multiple computations that return optional value:
const readField = treename == null ? Maybe : Maybe const readPath = restlength === 0 ? : Maybechain readPath "Users" "gozala" "Documents" "Users": "gozala": "Documents": "maybe.js" ; // => ["maybe.js"] readPath "Users" "Dave" "stuff" "Users": "gozala": "Documents": "maybe.js" ; // => null
Install
npm install value-maybe