Skip to content

Instantly share code, notes, and snippets.

@mcsf
Last active January 22, 2016 23:31
Show Gist options
  • Save mcsf/7f93ec75cda72c621029 to your computer and use it in GitHub Desktop.
Save mcsf/7f93ec75cda72c621029 to your computer and use it in GitHub Desktop.
Cartesian product
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