Last active
January 9, 2018 15:26
-
-
Save yangsu/a1737ef1b323835098d4 to your computer and use it in GitHub Desktop.
Javascript Generator function (ES2015) for creating cartesian product of multiple lists
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 *productHelper(lists, prefix = []) { | |
if (lists.length === 0) { | |
yield []; | |
} else { | |
const [head, ...rest] = lists; | |
for (let item of head) { | |
const newPrefix = prefix.concat(item); | |
if (rest.length) { | |
yield *productHelper(rest, newPrefix); | |
} else { | |
yield newPrefix; | |
} | |
} | |
} | |
} | |
function *product(...lists) { | |
yield *productHelper(lists); | |
} | |
for (let p of product([[1, 2], [3, 4], [5, 6]])) { | |
console.log(p); | |
} | |
// [ 1, 3, 5 ] | |
// [ 1, 3, 6 ] | |
// [ 1, 4, 5 ] | |
// [ 1, 4, 6 ] | |
// [ 2, 3, 5 ] | |
// [ 2, 3, 6 ] | |
// [ 2, 4, 5 ] | |
// [ 2, 4, 6 ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
doesn't work as it but it is not far.
the function *product(...lists)
needs to befunction *product(lists)
.