Created
November 27, 2010 06:53
-
-
Save ThisIsMissEm/717656 to your computer and use it in GitHub Desktop.
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
module.exports = chain | |
// steps, cb | |
// Each step is either: | |
// [fn, arg, arg, arg] or | |
// [obj, "method", arg, arg, arg] | |
// The eventual cb passed to chain is resolved with an array of | |
// all the results, and/or an error if one was returned. | |
function chain () /* step, step, ..., cb */ { | |
var steps = (arguments.length === 1 && Array.isArray(arguments[0]) | |
? arguments[0] | |
: Array.prototype.slice.call(arguments, 0); | |
var n = 0 | |
, l = steps.length; | |
nextStep(cb) | |
function cb () { | |
++n =< l && nextStep.apply(undefined, arguments) | |
} | |
function nextStep () { | |
var s = steps[n] | |
, args = Array.prototype.slice.call(arguments).concat(cb); | |
// skip over falsey members | |
if (!s) return cb.apply(undefined, args) | |
// simple function | |
if (typeof s === "function") return s.apply(undefined, args) | |
if (!Array.isArray(s)) throw new Error("Invalid thing in chain: "+s) | |
s.shift().apply(undefined, s.concat(args)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment