Created
July 31, 2020 19:39
-
-
Save dsetzer/f9fb87ab70f6423344cb1cf52b197b19 to your computer and use it in GitHub Desktop.
Generate all possible parameter combinations using cartesian product.
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
function cartesian(...args) { | |
let r = [], max = args.length - 1; | |
let step = (arr, i) => { | |
for (let j = 0, l = args[i].length; j < l; j++) { | |
let a = arr.slice(0); | |
a.push(args[i][j]); | |
if (i === max) r.push(a); else step(a, i + 1); | |
} | |
} | |
step([], 0); | |
return r; | |
} | |
// Example: | |
let combos = cartesian([1,2,3],[100,200,300], ['A','B','C'], [true, false]); | |
console.log(JSON.stringify(combos)); | |
// Output: | |
//'[[1,100,"A",true],[1,100,"A",false],[1,100,"B",true],[1,100,"B",false],[1,100,"C",true], | |
// [1,100,"C",false],[1,200,"A",true],[1,200,"A",false],[1,200,"B",true],[1,200,"B",false], | |
// [1,200,"C",true],[1,200,"C",false],[1,300,"A",true],[1,300,"A",false],[1,300,"B",true], | |
// [1,300,"B",false],[1,300,"C",true],[1,300,"C",false],[2,100,"A",true],[2,100,"A",false], | |
// [2,100,"B",true],[2,100,"B",false],[2,100,"C",true],[2,100,"C",false],[2,200,"A",true], | |
// [2,200,"A",false],[2,200,"B",true],[2,200,"B",false],[2,200,"C",true],[2,200,"C",false], | |
// [2,300,"A",true],[2,300,"A",false],[2,300,"B",true],[2,300,"B",false],[2,300,"C",true], | |
// [2,300,"C",false],[3,100,"A",true],[3,100,"A",false],[3,100,"B",true],[3,100,"B",false], | |
// [3,100,"C",true],[3,100,"C",false],[3,200,"A",true],[3,200,"A",false],[3,200,"B",true], | |
// [3,200,"B",false],[3,200,"C",true],[3,200,"C",false],[3,300,"A",true],[3,300,"A",false], | |
// [3,300,"B",true],[3,300,"B",false],[3,300,"C",true],[3,300,"C",false]]' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment