Created
July 23, 2013 20:50
-
-
Save madbence/6066054 to your computer and use it in GitHub Desktop.
Some fun with Monads
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
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