Last active
February 12, 2018 23:13
-
-
Save PatrickJS/5844374 to your computer and use it in GitHub Desktop.
Ajax Monad
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
function Monad() { | |
var prototype = Object.create(null); | |
function unit(value) { | |
var monad = Object.create(prototype); | |
monad.bind = function(func, args) { | |
return func.apply(undefined, [value].concat(Array.prototype.slice.apply(args || []))); | |
} | |
return monad; | |
} | |
unit.lift = function(name, func) { | |
prototype[name] = function(...args) { | |
return unit(this.bind(func, args)); | |
}; | |
return unit; | |
}; | |
unit.method = function(name, func) { | |
prototype[name] = func; | |
return unit | |
} | |
return unit; | |
} | |
========= | |
var ajax = MONAD().lift('alert', alert); | |
var monad = ajax('Hello world.'); | |
monad.bind(alert); | |
monad.alert(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Props to Douglas Crockford "Monads and Gonads".