Created
October 28, 2011 19:57
-
-
Save FestivalBobcats/1323387 to your computer and use it in GitHub Desktop.
Underscore.js implementation of 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
function cartesianProductOf(){ | |
return _.reduce(arguments, function(mtrx, vals){ | |
return _.reduce(vals, function(array, val){ | |
return array.concat( | |
_.map(mtrx, function(row){ return row.concat(val); }) | |
); | |
}, []); | |
}, [[]]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! You should make innermost clause:
otherwise if someone (like me) is trying to use this on arrays of arrays, JS unwelcomely flattens the array. (And it's just as safe this way for when you're not passing arrays)