Skip to content

Instantly share code, notes, and snippets.

@xulapp
Created April 17, 2011 04:01
Show Gist options
  • Select an option

  • Save xulapp/923747 to your computer and use it in GitHub Desktop.

Select an option

Save xulapp/923747 to your computer and use it in GitHub Desktop.
permutate
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