Skip to content

Instantly share code, notes, and snippets.

@AprilSylph
Created August 4, 2020 14:20
Show Gist options
  • Save AprilSylph/1d963f59d60ae21d3f22f82a9c70a79a to your computer and use it in GitHub Desktop.
Save AprilSylph/1d963f59d60ae21d3f22f82a9c70a79a to your computer and use it in GitHub Desktop.
Cartesian product without recursion
/**
* @param {...Object[]} arrays - one or more arrays
* @return {Object[]} The Cartesian product of the arrays
*/
const cartesian = (...arrays) => {
let product = arrays.shift().map(x => [x]);
for (const currentArray of arrays) {
const newProduct = [];
for (const currentValue of currentArray) {
for (const x of product) {
newProduct.push([...x, currentValue]);
}
}
product = newProduct;
}
return product;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment