如何将值应用于javascript中所有组合的模式?

如何将值应用于javascript中所有组合的模式?,javascript,pattern-matching,combinations,Javascript,Pattern Matching,Combinations,我有以下二维数组输入: var arr = [ ['A', ['Sun','Moon']], ['B', ['Cat','Dog']], ['C', ['John','Peter','Zora']] ]; 使用该输入,我希望将所有组合应用于javascript中的给定模式: 模式中的占位符采用以下格式:$(名称) 以下是一些示例模式及其结果: 图案可以是任意组合(带有重复占位符)和任意长度 有人能帮我用javascript编写一个算法吗 谢

我有以下二维数组输入:

 var arr = [ 
        ['A', ['Sun','Moon']],
        ['B', ['Cat','Dog']],
        ['C', ['John','Peter','Zora']]
 ];
使用该输入,我希望将所有组合应用于javascript中的给定模式:

模式中的占位符采用以下格式:$(名称)

以下是一些示例模式及其结果:

图案可以是任意组合(带有重复占位符)和任意长度

有人能帮我用javascript编写一个算法吗


谢谢。

您可以一次替换一个占位符

示例:从阵列中的图案开始:

["$(A) / $(A)"]
替换第一个占位符并为所有组合创建字符串:

["Sun / $(A)", "Moon / $(A)"]
["Sun / Sun", "Sun / Moon", "Moon / Sun", "Moon / Moon"]
替换每个字符串中的下一个占位符,并为所有组合创建字符串:

["Sun / $(A)", "Moon / $(A)"]
["Sun / Sun", "Sun / Moon", "Moon / Sun", "Moon / Moon"]
重复此操作,直到不再有占位符


演示:

您可以使用递归函数来完成此操作

首先,必须从字符串中提取名称。可以使用正则表达式执行此操作:

var regex = /\$\(([A-Z])\)/g,
    names = [], match;

while(match = regex.exec(pattern)) {
    names.push(match[1]);
}
然后将此列表和值的映射传递给递归迭代名称的函数:

function create_combinations(pattern, names, map, index) {
    index = index || 0;
    var name = names[index],
        values = map[name],
        needle = "$(" + name + ")",
        combinations = [],
        sub;

    if (index === names.length - 1) {
        for (var i = 0, l = values.length; i < l; i++) {
            combinations.push(pattern.replace(needle, values[i]));
        }
    }
    else {
        for (var i = 0, l = values.length; i < l; i++) {
            sub = pattern.replace(needle, values[i]);
            combinations = combinations.concat(create_combinations(sub, names, map, index + 1));
        }
    }
    return combinations;
}
然后用

create_combinations(pattern, names, map);