Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Forked from andyhd/maybe-monad.js
Last active December 14, 2015 20:09
Show Gist options
  • Save hughfdjackson/5141769 to your computer and use it in GitHub Desktop.
Save hughfdjackson/5141769 to your computer and use it in GitHub Desktop.
var peeps = { hugh: { name: 'hugh jackson' } }
var titleCase = function(str){
return str.split(' ').map(function(str){ return str.substr(0, 1).toUpperCase() + str.substr(1) }).join(' ')
}
var val = maybe(peeps)
.map(function(peeps){ return peeps.tahir })
.map(function(peep){ return peep.name })
.map(titleCase)
.getOrElse('couldn\'t find person')
val //= couldn't find person
var val2 = maybe(peeps)
.map(function(peeps){ return peeps.hugh })
.map(function(peep){ return peep.name })
.map(titleCase)
.getOrElse('couldn\'t find person')
val2 //= Hugh Jackson
function maybe(value) {
var obj = null;
function isEmpty() { return value === undefined || value === null }
function nonEmpty() { return !isEmpty() }
obj = {
map: function (f) { return isEmpty() ? obj : maybe(f(value)) },
getOrElse: function (n) { return isEmpty() ? n : value },
isEmpty: isEmpty,
nonEmpty: nonEmpty
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment