在Javascript中获取所有可能的l33t组合的数组

xd1*_*936 6 javascript arrays string prototype str-replace

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

var equiv = {
  "a": "4",
  "b": "8",
  "e": "3",
  "i": "1",
  "l": "1",
  "o": "0",
  "t": "7"
}
Run Code Online (Sandbox Code Playgroud)

我想定义一个String.prototype函数,如:

String.prototype.l33tCombonations = function()
{
    var toReturn = [];

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

    return toReturn;
}
Run Code Online (Sandbox Code Playgroud)

所以我可以提供类似的东西"tomato".l33tCombinations()并回来:

["tomato", "t0mato", "t0mat0", "tomat0", "toma7o", "t0ma7o", "t0m470", ...].
Run Code Online (Sandbox Code Playgroud)

订单并不重要.思考?

Jon*_*lms 3

我会使用递归方法,逐个字符遍历字符串:

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"));
Run Code Online (Sandbox Code Playgroud)

如果您确实在原型上需要它,那也是可能的,但我不建议这样做:

 String.prototype.l33t = function() {
   return [...l33t(this)];
 };

 console.log("stuff".l33t());
Run Code Online (Sandbox Code Playgroud)