Skip to content

Instantly share code, notes, and snippets.

@madbence
Created July 23, 2013 20:50
Show Gist options
  • Save madbence/6066054 to your computer and use it in GitHub Desktop.
Save madbence/6066054 to your computer and use it in GitHub Desktop.
Some fun with Monads
function Maybe(value) {
this.value = value;
}
Maybe.prototype.map = function _map(fn, ctx) {
ctx = ctx || {};
return this.value === null ? new Maybe(this.value) : new Maybe(fn.call(ctx, this.value));
};
function Either(left, right) {
this.left = left;
this.right = right;
}
Either.prototype.map = function _map(fn, ctx) {
ctx = ctx || {};
return this.right !== null ?
new Either(this.left, fn.call(ctx, this.right)) :
new Either(fn.call(ctx, this.left), null);
};
function Promise(val) {
this.value = val;
}
Promise.prototype.map = function _map(fn, ctx) {
ctx = ctx || {};
var self = this;
setTimeout(function() {
fn(self.value);
}, 1000);
return this;
};
function map(val, fn, ctx) {
ctx = ctx || {};
return val.map ? val.map(fn, ctx) : fn(val, ctx);
}
function greet(name) {
console.log('Hello ' + name + '!');
}
map(new Maybe('Bob'), greet);
map(new Maybe(null), greet);
map(new Either('Anonymous', 'Bob'), greet);
map(new Either('Anonymous', null), greet);
map(new Promise('Bob'), greet);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment