Skip to content

Instantly share code, notes, and snippets.

@DrBoolean
Created August 18, 2015 18:11
Show Gist options
  • Select an option

  • Save DrBoolean/66e5923a830462c5f88d to your computer and use it in GitHub Desktop.

Select an option

Save DrBoolean/66e5923a830462c5f88d to your computer and use it in GitHub Desktop.
Lazy wrap/value comonad from lodash/underscore
// Helpers
//=================
var compose = function(f,g) {
return function(x) {
return f(g(x))
}
}
var id = function(x) { return x }
// Wrapper
//=================
// make the type that holds our eventual computation f and our value x
var _ = function(x, f) {
this.x = x;
this.f = f;
}
// start up with x and the identity fn
_.from = function(x) {
return new _(x, id);
}
// run the f on the x
_.prototype.extract = function() {
return this.f(this.x);
}
// compose our previous f that drops out of the wrapper, then put it back in with from
// the eager version would just be _.from(f(this));
_.prototype.extend = function(f) {
return new _(this.x, compose(f, compose(_.from, this.f)));
}
// in lodash these typically dispatch on w.x or just w depending on if it's wrapped or not
_.toUpper = function(w) { return w.x.toUpperCase() }
_.last = function(w) { return w.x[w.x.length-1] }
var result = _.from("I am not a holla back girl").extend(_.toUpper).extend(_.last).extract()
console.log('result', result);
// L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment