Skip to content

Instantly share code, notes, and snippets.

@crshmk
Created March 4, 2018 14:54
Show Gist options
  • Save crshmk/9a5a196e67b75866e742348951be3d70 to your computer and use it in GitHub Desktop.
Save crshmk/9a5a196e67b75866e742348951be3d70 to your computer and use it in GitHub Desktop.
Functor chaining with null handler
/**
* 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