在JavaScript中创建组合

Gre*_*ida 3 javascript algorithm combinations cartesian-product

可以说我在Javascript中有几组选项

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];
Run Code Online (Sandbox Code Playgroud)

什么是一种有效的算法,可以在这样的数组中获得这些选项的所有组合

["red and small and heavy", "red and small and light", "red and medium and heavy" ...]
Run Code Online (Sandbox Code Playgroud)

这是一个警告

此功能必须能够采用任意数量的选项

我有一种感觉,这样做的正确方法是通过某种树遍历,但现在还没有完全考虑到这一点,我还没有喝咖啡

AKX*_*AKX 7

function permutations(choices, callback, prefix) {
    if(!choices.length) {
        return callback(prefix);
    }
    for(var c = 0; c < choices[0].length; c++) {
        permutations(choices.slice(1), callback, (prefix || []).concat(choices[0][c]));
    }
}

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];

permutations([color, size, weight], console.log.bind(console));
Run Code Online (Sandbox Code Playgroud)

似乎工作......

[ 'red', 'small', 'heavy' ]
[ 'red', 'small', 'light' ]
[ 'red', 'medium', 'heavy' ]
[ 'red', 'medium', 'light' ]
[ 'red', 'large', 'heavy' ]
[ 'red', 'large', 'light' ]
[ 'blue', 'small', 'heavy' ]
[ 'blue', 'small', 'light' ]
[ 'blue', 'medium', 'heavy' ]
[ 'blue', 'medium', 'light' ]
[ 'blue', 'large', 'heavy' ]
[ 'blue', 'large', 'light' ]
[ 'green', 'small', 'heavy' ]
[ 'green', 'small', 'light' ]
[ 'green', 'medium', 'heavy' ]
[ 'green', 'medium', 'light' ]
[ 'green', 'large', 'heavy' ]
[ 'green', 'large', 'light' ]
[ 'yellow', 'small', 'heavy' ]
[ 'yellow', 'small', 'light' ]
[ 'yellow', 'medium', 'heavy' ]
[ 'yellow', 'medium', 'light' ]
[ 'yellow', 'large', 'heavy' ]
[ 'yellow', 'large', 'light' ]
Run Code Online (Sandbox Code Playgroud)