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

标签 javascript arrays string prototype str-replace

我有一个字符串,我想使用以下替换获取所有可能的 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", ...].

顺序并不重要。想法?

最佳答案

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

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)上也是可能的,但我不建议这样做:

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

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

关于javascript - 在 Javascript 中获取所有可能的 l33t 组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54240759/

相关文章:

javascript - 在 SAPUI5 上刷新整个页面的正确方法是什么(ESLINT :(sap-no-location-reload))?

javascript - 了解 JS 事件循环

c# - 反转对象数组

c - 如何在C中输入由换行符分隔的两个字符串

ruby - 在 Vagrant 配置期间使用 Sed 将行附加到文件

php - 字符串解析帮助

javascript - 如何滚动 .list-group 将导航栏留在顶部

javascript - 我正在尝试通过验证创建此登录/注册表单

Javascript - 如何根据第二个数组的顺序对一个数组进行比较和排序?

php - 从字符串中删除所有 html 标签的最佳方法是什么?