Skip to content

Instantly share code, notes, and snippets.

@ties
Created March 28, 2018 09:52
Show Gist options
  • Save ties/ce0b2c3e857be581aa504cb13f64315f to your computer and use it in GitHub Desktop.
Save ties/ce0b2c3e857be581aa504cb13f64315f to your computer and use it in GitHub Desktop.
// @flow
//
// flow-annotated variant of https://github.com/izaakschroeder/cartesian-product
//
function product<T>(...elements: $ReadOnlyArray<$ReadOnlyArray<T>>): $ReadOnlyArray<$ReadOnlyArray<T>> {
const end = elements.length - 1;
const result: Array<Array<T>> = [];
function addTo(curr: Array<T>, start: number) {
const first = elements[start];
const last = (start === end);
for (let i = 0; i < first.length; ++i) {
var copy = curr.slice();
copy.push(first[i]);
// Handle the base case of the recursion, otherwise, make recursive call.
if (last) {
result.push(copy);
} else {
addTo(copy, start + 1);
}
}
}
// Split cases: empty inputs or start in at first element.
if (elements.length) {
addTo([], 0);
} else {
result.push([]);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment