Created
October 18, 2012 14:08
-
-
Save vol4ok/3912061 to your computer and use it in GitHub Desktop.
chain
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
$.chain = function() { | |
var tasks | |
, args = [] | |
, error = noop; | |
if(arguments.length === 3) { | |
args = $.isArray(arguments[0]) ? arguments[0] : [arguments[0]]; | |
tasks = arguments[1]; | |
error = arguments[2]; | |
} else if(arguments.length === 2) { | |
if ($.isArray(arguments[1])) { | |
args = $.isArray(arguments[0]) ? arguments[0] : [arguments[0]]; | |
tasks = arguments[1]; | |
} else { | |
tasks = arguments[0]; | |
error = arguments[1]; | |
} | |
} else if(arguments.length === 1) { | |
args = [] | |
tasks = arguments[0]; | |
error = noop; | |
} else | |
return false; | |
var iterate, len | |
, i = 0; | |
tasks = $.map(tasks, function(task, key) { | |
return {key: key, task: task}; | |
}); | |
len = tasks.length; | |
(iterate = function() { | |
console.log("iterate", i, len); | |
if (++i > len) return; | |
var args = $.slice.call(arguments); | |
try { | |
tasks[i-1].task.apply(this, args.concat([iterate])); | |
} catch(err) { | |
error(err); | |
} | |
}).apply(this, args); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment