Skip to content

Instantly share code, notes, and snippets.

@jackwilsdon
Created July 26, 2018 15:24
Show Gist options
  • Save jackwilsdon/9bf2a308693e22125b91f0dbddd8d54e to your computer and use it in GitHub Desktop.
Save jackwilsdon/9bf2a308693e22125b91f0dbddd8d54e to your computer and use it in GitHub Desktop.
const cartesianProduct = arrays => {
if (arrays.length === 0) {
return [];
}
// Find the next set of combinations after this first array.
const nextCombinations = cartesianProduct(arrays.slice(1));
// Add values from the current array to the next combinations.
return arrays[0].reduce(
(result, value) => [
...result,
...(nextCombinations.length
? nextCombinations.map(combination => [value, ...combination])
: [[value]]),
],
[],
);
};
export default cartesianProduct;
import cartesianProduct from './cartesianProduct';
it('handles empty arrays correctly', () => {
expect(cartesianProduct([[]])).toEqual([]);
expect(cartesianProduct([[], [], []])).toEqual([]);
});
it('handles a single populated array correctly', () => {
expect(cartesianProduct([[1, 2, 3]])).toEqual([[1], [2], [3]]);
});
it('handles mixed empty and populated arrays correctly', () => {
expect(cartesianProduct([[1, 2, 3], [], [], []])).toEqual([[1], [2], [3]]);
});
it('handles multiple populated arrays', () => {
expect(cartesianProduct([[1, 2, 3], [4, 5, 6]])).toEqual([
[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6],
]);
});
it('handles multiple populated arrays with mixed types', () => {
expect(cartesianProduct([['a', 'b', 3], [undefined, true]])).toEqual([
['a', undefined],
['a', true],
['b', undefined],
['b', true],
[3, undefined],
[3, true],
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment