Enumerate Function
by donabrams
HTML
<div id="a">EXAMPLE:</div>
JavaScript
var exampleFunction = function(a, b, c) {
$(a).append("<p>" + b + "->" + c + "</p>");
};
exampleFunction("#a", "example", 1);
//
// This function goes through each entry in the array values
// and if it is an array, Calls func once per value in the array.
//
// The real use of this function is to easily allow functions that normally take
// single values to be expanded without any real work. See Ruleset.addValidator
// in http://jsfiddle.net/donabrams/dMNee/8/ for an example.
//
// Obviously this doesn't work if func is expecting an Array!
//
// returns no value.
//
var enumerateFunctionWorker;
var enumerateFunction = function(func, values, context) {
enumerateFunctionWorker(func, values, [], (typeof context == "undefined" ? this : context));
};
enumerateFunctionWorker = function(func, values, valueStack, context) {
if (!values || !values.length) {
func.apply(context, valueStack);
} else if ($.isArray(values[0])) {
var i;
for (i = 0; i < values[0].length; i++) {
var newStack = valueStack.slice(0);
newStack.push(values[0][i]);
var remainingValues = values.length == 1 ? [] : values.slice(1);
enumerateFunctionWorker(func, remainingValues, newStack, context);
}
} else {
var newStack = valueStack.slice(0);
newStack.push(values[0]);
var remainingValues = values.length == 1 ? [] : values.slice(1);
enumerateFunctionWorker(func, remainingValues, newStack, context);
}
};
var enumeratedExampleFunction = function(a, b, c) {
enumerateFunction(exampleFunction, [a, b, c]);
};
enumeratedExampleFunction("#a", "base", "case");
enumeratedExampleFunction("#a", [1, 2, 3, 4], [5, 6, 7, 8]);