Skip to content

Instantly share code, notes, and snippets.

@andredublin
Last active May 17, 2016 19:29
Show Gist options
  • Save andredublin/2db4bdba278e23a06eb17e69e043e65e to your computer and use it in GitHub Desktop.
Save andredublin/2db4bdba278e23a06eb17e69e043e65e to your computer and use it in GitHub Desktop.
maybe in js
var Maybe = function(x) {
this.__value = x;
};
Maybe.of = function(x) {
return new Maybe(x);
};
Maybe.prototype.isNothing = function() {
return (this.__value === null || this.__value === undefined);
};
Maybe.prototype.map = function(f) {
return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this.__value));
};
Maybe.of('Malkovich Malkovich').map(match(/a/ig));
//=> Maybe(['a', 'a'])
Maybe.of(null).map(match(/a/ig));
//=> Maybe(null)
Maybe.of({
name: 'Boris',
}).map(_.prop('age')).map(add(10));
//=> Maybe(null)
Maybe.of({
name: 'Dinah',
age: 14,
}).map(_.prop('age')).map(add(10));
//=> Maybe(24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment