Skip to content

Instantly share code, notes, and snippets.

@andyhd
Created January 16, 2012 01:02
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save andyhd/1618403 to your computer and use it in GitHub Desktop.
Save andyhd/1618403 to your computer and use it in GitHub Desktop.
Maybe monad in Javascript
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;
}
@Muzietto
Copy link

No Martini, no party. No bind, no monad. You may call it flatMap, but fixItOrElse("wrong, wrong, wrong")
@ptnplanet in this case return is maybe(value) itself

@dan-weaver
Copy link

I think this is just a functor no?

@nitindhar7
Copy link

@andyhd just created something similar to this for node called Giftbox here. Would love to hear your thoughts/feedback! Also motivated by Scala :)

@jhegedus42
Copy link

@Muzietto, lol ! how true :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment