Created
April 17, 2011 04:01
-
-
Save xulapp/923747 to your computer and use it in GitHub Desktop.
permutate
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
| function permutate(fn) { | |
| var result = []; | |
| var queue = [Array.slice(arguments, 1)]; | |
| while (queue.length) { | |
| var args = queue.shift(); | |
| for (var i = 0, len = args.length; i < len; i++) { | |
| var arg = args[i]; | |
| if (arg instanceof Array) break; | |
| } | |
| if (i === len) { | |
| result.push(fn.apply(this, args)); | |
| } else { | |
| for (var j = 0, len = arg.length; j < len; j++) { | |
| args[i] = arg[j]; | |
| queue.push(args.concat()); | |
| } | |
| } | |
| } | |
| return result; | |
| } | |
| permutate(function(a, b, c) a + b + c, [100, 200], [10, 20], [1, 2]).toSource(); | |
| // [111, 112, 121, 122, 211, 212, 221, 222] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment