Created
October 26, 2011 17:30
-
-
Save donabrams/1317086 to your computer and use it in GitHub Desktop.
Enumerated Function
This file contains hidden or 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
| 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]); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsfiddle.net/donabrams/Te7mu/