Skip to content

Instantly share code, notes, and snippets.

@yshnb
Created June 19, 2015 16:27
Show Gist options
  • Select an option

  • Save yshnb/b64d6135a86b7e65d29a to your computer and use it in GitHub Desktop.

Select an option

Save yshnb/b64d6135a86b7e65d29a to your computer and use it in GitHub Desktop.
Option Monad in JavaScript
/**
* 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