Skip to content

Instantly share code, notes, and snippets.

@hitsthings
Created September 8, 2013 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hitsthings/6482549 to your computer and use it in GitHub Desktop.
Save hitsthings/6482549 to your computer and use it in GitHub Desktop.
var toArray = Function.prototype.call.bind(Array.prototype.slice);
function partial(fn/*, ...args*/) {
var args = [].slice.call(arguments, 1);
return function() {
var lastArgs = toArray(arguments);
return fn.apply(this, args.concat(lastArgs));
};
}
function partialRight(fn/*, ...args*/) {
var args = [].slice.call(arguments, 1);
return function() {
var firstArgs = [].slice.call(arguments);
return fn.apply(this,
firstArgs.concat(args));
};
}
function handleError(errback, callback) {
return function(err) {
err ?
errback(err) :
callback.apply(this,
[].slice.call(arguments, 1));
};
}
function composeAsync() {
var fns = toArray(arguments);
return function() {
var args = toArray(arguments);
var next = args.pop();
var nextOnError = partial(handleError, next);
var callFns = fns.map(nextOnError);
var call = callFns.reduce(function(next, fn) {
return partialRight(fn, next);
}, next);
call.apply(this, [ null ].concat(args));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment