Created
August 4, 2020 14:20
-
-
Save AprilSylph/1d963f59d60ae21d3f22f82a9c70a79a to your computer and use it in GitHub Desktop.
Cartesian product without recursion
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
/** | |
* @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