Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active February 12, 2018 23:13
Show Gist options
  • Save PatrickJS/5844374 to your computer and use it in GitHub Desktop.
Save PatrickJS/5844374 to your computer and use it in GitHub Desktop.
Ajax Monad
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();
@egarson
Copy link

egarson commented Feb 12, 2018

Props to Douglas Crockford "Monads and Gonads".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment