Skip to content

Instantly share code, notes, and snippets.

@yangsu
Last active January 9, 2018 15:26
Show Gist options
  • Save yangsu/a1737ef1b323835098d4 to your computer and use it in GitHub Desktop.
Save yangsu/a1737ef1b323835098d4 to your computer and use it in GitHub Desktop.
Javascript Generator function (ES2015) for creating cartesian product of multiple lists
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 ]
@LBdN
Copy link

LBdN commented Jan 9, 2018

doesn't work as it but it is not far. the function *product(...lists) needs to be function *product(lists).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment