Skip to content

Instantly share code, notes, and snippets.

@webbower
Last active August 29, 2015 14:05
Show Gist options
  • Save webbower/d4ffd976de9cf0a8d8b1 to your computer and use it in GitHub Desktop.
Save webbower/d4ffd976de9cf0a8d8b1 to your computer and use it in GitHub Desktop.
Maybe monad in JS
// Requires testers.js for existy() and isRealNaN()
/**
* Maybe Monad (chainable, failure tolerant)
*
* Maybe(value, failOn).bind(function(value) { return value * value; }).value()
*/
var Maybe = function Maybe(val) {
if (!(this instanceof Maybe)) {
return new Maybe(val);
}
this.value = val;
};
Maybe.unit = function unit(value) {
return new Maybe(value);
};
Maybe.fnBind = function fnBind(fn) {
return function() {
return fn(arguments[0].value);
};
};
Maybe.prototype.mBind = function mBind(fn) {
return Maybe.unit(existy(this.value) ? fn(this.value) : null);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment