Created
June 19, 2015 16:27
-
-
Save yshnb/b64d6135a86b7e65d29a to your computer and use it in GitHub Desktop.
Option Monad in JavaScript
This file contains hidden or 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
| /** | |
| * Option Monad in JavaScript | |
| */ | |
| function Option() { | |
| } | |
| function Some(value) { | |
| this.value = value; | |
| } | |
| function None() { | |
| } | |
| Option.unit = function(value) { | |
| if (value !== undefined && this.value !== null) { | |
| return new Some(value); | |
| } else { | |
| return new None(); | |
| } | |
| }; | |
| Option.prototype.bind = function(func) { | |
| if (this instanceof Some) { | |
| return Option.unit(func(this.value)) | |
| } else { | |
| return None.unit(); | |
| } | |
| }; | |
| Option.prototype.get = function() { | |
| if (this instanceof Some) { | |
| return this.value; | |
| } else { | |
| return null; | |
| } | |
| }; | |
| Some.prototype = None.prototype = Object.create(Option.prototype); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment