我有一个字符串,希望在使用以下替换项时获得所有可能的replace -ment组合:

var equiv = {
  "a": "4",
  "b": "8",
  "e": "3",
  "i": "1",
  "l": "1",
  "o": "0",
  "t": "7"
}

我想定义一个String.prototype函数,例如:
String.prototype.l33tCombonations = function()
{
    var toReturn = [];

    for (var i in equiv)
    {
        // this.???
        // toReturn.push(this???)
    }

    return toReturn;
}

所以我可以输入类似"tomato".l33tCombinations()的代码并返回:
["tomato", "t0mato", "t0mat0", "tomat0", "toma7o", "t0ma7o", "t0m470", ...].

顺序并不重要。有什么想法吗?

最佳答案

我将使用一种递归方法,通过char遍历字符串char:

const toL33t = { "a": "4", "b": "8",  "e": "3",  "i": "1", "l": "1",  "o": "0",  "t": "7" };

function* l33t(string, previous = "") {
  const char = string[0];
  // Base case: no chars left, yield previous combinations
  if(!char) {
    yield previous;
    return;
  }
  // Recursive case: Char does not get l33t3d
  yield* l33t(string.slice(1), previous + char);
  // Recursive case: Char gets l33t3d
  if(toL33t[char])
    yield* l33t(string.slice(1), previous + toL33t[char]);
}

console.log(...l33t("tomato"));


如果您确实还在原型(prototype)possibl3上需要它,但我不建议您这样做:
 String.prototype.l33t = function() {
   return [...l33t(this)];
 };

 console.log("stuff".l33t());

08-17 07:10