Last active
August 29, 2015 14:05
-
-
Save webbower/d4ffd976de9cf0a8d8b1 to your computer and use it in GitHub Desktop.
Maybe monad in JS
This file contains 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
// 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