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