monady
Composable monads for functional async flow.
Name
It's like Monday, but misspelled :) Also, apparently, it's Polish for monads.
Installation
$ npm install monady
Monads
Identity
Identity
always has a value.
identity(x)
type constructor
assert;assert;assert;
bind(x => )
or then(x => )
assert;
lift(x => )
const lifted = Identity;;assert; ;assert;
lift2((x, y) => )
const lifted = Identity;;assert;
map(x => )
;assert;
Maybe, Just and Nothing
Maybe
resolves to either Just
or Nothing
depending on whether a value is passed to the type constructor. Nothing
is not thenable but can be bound, lifted or mapped.
maybe(x)
type constructor
just(x)
nothing
;assert;assert; ;assert; ;assert; ;assert;
bind(x => )
or then(x => )
assert; assert; // nothing is not thenableassert;
lift(x => )
const lifted1 = Just;;assert; ;assert; const lifted2 = Nothing;;assert; ;assert;
lift2((x, y) => )
const lifted1 = Just;;assert; const lifted2 = Nothing;;assert;
map(x => )
;assert; assert;
Either
Either
returns either left
(default) or right
, if it is set.
either(left, right)
type constructor
assert;assert;assert;
bind(x => )
or then(x => )
assert;assert;
lift(x => )
const lifted = Either;;assert; ;assert; ;assert;
lift2((x, y) => )
const lifted = Either;;assert;
map(x => )
;assert; ;assert;
RejectWhen
RejectWhen
rejects a value on bind
(or then
) with error
when condition when
is met.
rejectWhen(when, error, value)
type constructor
bind(x => )
or then(x => )
const rejectWhenNothing = rejectWhen; // resolves valueconst result1 = ;assert; // resolve maybe valueconst result2 = ;assert; // rejects nothing; // rejects maybe nothing;
lift(x => )
const lifted = RejectWhen;;assert;
lift2((x, y) => )
const lifted = RejectWhen;;assert;
map(x => )
;assert;
Examples
Rejecting value when it is Nothing
using RejectWhen
and maybe
.
const rejectWhenNothing = RejectWhen; const result = ;assert; ;
Rejecting value when it is not set using RejectWhen
and either
.
const rejectWhenError = RejectWhen; const result = ;assert; ;
Using generator functions and lifting to avoid explicit null checks.
{ const req = thisrequest; // Lift Maybe into RejectWhen context const rejectWhenNothing = RejectWhen; const user =
Using generator functions with ramda for compose and curry to avoid explicit null checks.
{ const req = thisrequest; const rejectWhenNothing = R val === nothing 'value rejected'; // maybe wraps Promise from findOne and is in turn wrapped in // rejectWhenNothing. const getUser = R; const user = ; // If user is not found Maybe will return nothing and be rejected by // RejectWhen so code after yield will not run. Hence no check if user // exists is needed. // Do something with user}
License
MIT