Skip to content

Instantly share code, notes, and snippets.

@ChrisTM
Last active October 10, 2015 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisTM/3691819 to your computer and use it in GitHub Desktop.
Save ChrisTM/3691819 to your computer and use it in GitHub Desktop.
N-Ary/Multiple-List Cartesian Product
/* N-ary cartesian product.
* Input: any number of lists
* Output: the cartesian product of the above lists as list of lists
* Example: cartesianProduct([1, 2], ['cat']) -> [ [1, 'cat'], [2, 'cat'] ]
*/
var cartesianProduct = function () {
function addNextList (tuples, list) {
var result = [];
tuples.forEach(function (tuple) {
list.forEach(function (item) {
result.push(tuple.concat(item));
});
});
return result;
}
var lists = Array.prototype.slice.call(arguments, 0);
return lists.reduce(addNextList, [[]]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment