Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created October 26, 2011 17:30
Show Gist options
  • Select an option

  • Save donabrams/1317086 to your computer and use it in GitHub Desktop.

Select an option

Save donabrams/1317086 to your computer and use it in GitHub Desktop.
Enumerated Function
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]);
@donabrams
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment