Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Array of All Possible l33t Combinations in Javascript

I have a string that I'd like to get all possible replace-ment combinations on using the following substitutions:

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

I would like to define a String.prototype function, something like:

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

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

    return toReturn;
}

So I could feed in something like "tomato".l33tCombinations() and get back:

["tomato", "t0mato", "t0mat0", "tomat0", "toma7o", "t0ma7o", "t0m470", ...].

Order is not important. Thoughts?

like image 913
xd1936 Avatar asked Jan 17 '19 16:01

xd1936


2 Answers

I would use a recursive approach, that traverses the string char by 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"));

If you really need it on the prototype thats also possibl3, but I wouldn't recommend that:

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

 console.log("stuff".l33t());
like image 50
Jonas Wilms Avatar answered Sep 18 '22 10:09

Jonas Wilms


You could take a cartesian product for generating the wanted values.

function leet(string) {
    const
        cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
        code = { a: "4", b: "8", e: "3", i: "1", l: "1", o: "0", t: "7" };

    return Array
         .from(string, c => c in code ? [c, code[c]] : [c])
         .reduce(cartesian)
         .map(a => a.join(''));
}

console.log(leet('tomatoe'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 38
Nina Scholz Avatar answered Sep 21 '22 10:09

Nina Scholz