Created
March 4, 2018 14:54
-
-
Save crshmk/9a5a196e67b75866e742348951be3d70 to your computer and use it in GitHub Desktop.
Functor chaining with null handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Test for null when chaining functor wrappers | |
* If not null, call chained functions on passed value | |
* If null occurs, disregard the function and pass along null | |
* When folding value, provide error and success handlers | |
*/ | |
// functor setup | |
const Call = x => | |
({ | |
map: f => Call(f(x)), | |
fold: (f, g) => g(x) | |
}) | |
const Pass = x => | |
({ | |
map: f => Pass(x), | |
fold: (f, g) => f(x) | |
}) | |
// null check | |
const check = x => x != null ? Call(x) : Pass(null); | |
// instance code | |
let ideas = { | |
mersault: "l'ennui est forte", | |
estragon: "we haven't any rope" | |
} | |
// function with potentially null return value | |
let idea = person => check(ideas[person]) | |
// functor chains | |
let getIdea = person => idea(person) | |
.map(x => x.toUpperCase()) | |
.fold(x => "that person isn't here", x => person + ' says ' + x) | |
getIdea('mersault') | |
// -> mersault says L'ENNUI EST FORTE | |
getIdea('joe') | |
// -> that person isn't here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment