Created
March 28, 2018 09:52
-
-
Save ties/ce0b2c3e857be581aa504cb13f64315f to your computer and use it in GitHub Desktop.
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
// @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