Skip to content

Instantly share code, notes, and snippets.

@michaelficarra

michaelficarra/Maybe.js Secret

Last active Aug 29, 2015
Embed
What would you like to do?
function Nothing() {}
function Just(x) {
this.valueOf = function(){ return x; };
}
Nothing.prototype.map = function(f) {
return this;
};
Just.prototype.map = function(f) {
return new Just(f(this.valueOf()));
};
Nothing.prototype.bind = function(f) {
return this;
};
Just.prototype.bind = function(f) {
return f(this.valueOf());
};
var Maybe = {
fromPossiblyNullValue: function(x) {
return x == null ? new Nothing() : new Just(x);
}
};
// double only numbers with odd parity
function doubleOddNumbers(x) {
// safe version of `return x&1 ? x * 2 : null;`
return x&1 ? new Just(x * 2) : new Nothing;
}
var a, safeA;
a = null;
safeA = Maybe.fromPossiblyNullValue(a);
safeA.bind(doubleOddNumbers); // Nothing
safeA.bind(doubleOddNumbers).bind(doubleOddNumbers); // Nothing
a = 2;
safeA = Maybe.fromPossiblyNullValue(a);
safeA.bind(doubleOddNumbers); // Nothing
safeA.bind(doubleOddNumbers).bind(doubleOddNumbers); // Nothing
a = 3;
safeA = Maybe.fromPossiblyNullValue(a);
safeA.bind(doubleOddNumbers); // Just(6)
safeA.bind(doubleOddNumbers).bind(doubleOddNumbers); // Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment