Last active
May 17, 2016 19:29
-
-
Save andredublin/2db4bdba278e23a06eb17e69e043e65e to your computer and use it in GitHub Desktop.
maybe 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
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