Last active
January 22, 2016 23:31
-
-
Save mcsf/7f93ec75cda72c621029 to your computer and use it in GitHub Desktop.
Cartesian product
This file contains 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
import { flatten } from 'lodash' | |
const flatMap = (xs, f) => flatten(xs.map(f)) | |
/** | |
* > cartesian([1, 2], [4, 5, 6], [7]) | |
* [ [ 1, 4, 7 ], | |
* [ 1, 5, 7 ], | |
* [ 1, 6, 7 ], | |
* [ 2, 4, 7 ], | |
* [ 2, 5, 7 ], | |
* [ 2, 6, 7 ] ] | |
*/ | |
export default function cartesian(...sets) { | |
return sets.reduce((product, nextSet) => | |
flatMap(product, set => | |
nextSet.map(item => [...set, item])), | |
[[]]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment