Learn how to easily encode and text text that uses a dictionary translations with the alphabet.

How to create a dictionary of the reversed alphabet to encode and decode text with JavaScript

In the last few days, a friend obtained the invitation to the Google Foobar challenge. As you may or may not know, the Foobar challenge is a secret hiring challenge from Google which you get when you match some search behavior on Google or check Google Documentation. People say that if you complete the challenge you have a high chance of being contacted by a Google recruiter!

Anyway, he was kind of busy with the work and he started the first challenge. He asked for some help so I decided to check what it was about. For the first challenge, he had to create a method in Python or Java that could encode a word according to a custom dictionary with the following rules:

  • The dictionary goes from a to z in lowercase.
  • The translation of the dictionary is inverse to the order of the alphabet. For example a=z, b=x and c=y.
  • Uppercase characters or any other special characters remain the same.

For example:

  • Encoded text: wrw blf hvv ozhg mrtsg'h vkrhlwv?
  • Decoded text: did you see last night's episode?

So, the idea and the solution are quite simple and therefore there are multiple ways to do it. In this article, I will show you the solution to this problem with vanilla JavaScript.

Decoding

For the approach of converting an encoded string with the given codification you can proceed like this:

Using a dictionary to translate characters

The first idea that you may have is to create a dictionary so you can easily iterate over a string and replace the characters with the one in your dictionary:

Translate Custom Dictionary

This implementation would be the following one. We can create the dictionary in multiple ways, we can use the premise of the ASCII table that indicates that the characters 97 to 122 are assigned to the alphabet in lowercase from a to z:

let dictionary = {};

for(let a = 97,b = 122;a <= 122;a++,b--){
    let char = String.fromCharCode(a);
    dictionary[char] = String.fromCharCode(b);
}

console.log(dictionary);

Or you can as well use the hardcoded string and reverse the alphabet assigning its translated value:

let alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
let inverseAlphabet = alphabet.slice().reverse();
let dictionary = {};

for(let i = 0; i < alphabet.length;i++){
    dictionary[alphabet[i]] = inverseAlphabet[i];
}

console.log(dictionary);

With any of these approaches, the dictionary variable will contain an object with the translation of the characters:

Dictionary Alphabet JavaScript

Now, the only thing you need to do is to iterate over the input string and replace the characters of the string with the created dictionary, for example, the following decoder method will do the job:

function decoder(encoded){
    let decoded = "";
    let alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
    let inverseAlphabet = alphabet.slice().reverse();
    let dictionary = {};

    for(let i = 0; i < alphabet.length;i++){
        dictionary[alphabet[i]] = inverseAlphabet[i];
    }

    for (let i = 0; i < encoded.length; i++) {
        let char = encoded.charAt(i);
        
        if(dictionary.hasOwnProperty(char)){
            decoded += dictionary[char];
        }else{
            decoded += char;
        }
    }

    return decoded;
}

You can run it with the example strings to check if it works:

// Returns: "did you see last night's episode?"
decoder("wrw blf hvv ozhg mrtsg'h vkrhlwv?");

It works, nice!

Using the plain ASCII conversion

However, there's a smoother approach keeping in mind the ASCII characters. For example, a shorter version of the method instead of creating the dictionary, this method performs a basic math operation to calculate the corresponding ASCII code for the translation. Knowing that the alphabet characters are between the ASCII codes 97 and 122, you can sum both numbers to add as limit and subtract the ASCII code of the character, to obtain the translation:

function decoder(encoded){
    let decoded = "";

    for (let i = 0; i < encoded.length; i++) {
        let char = encoded.charAt(i);
        let ascii = char.charCodeAt(0);

        if(ascii >= 97 && ascii <= 122){
            decoded += String.fromCharCode((122 + 97) -  char.charCodeAt(0));
        }else{
            decoded += char;
        }
    }

    return decoded;
}

Encoding

For the encoding step, you may follow the same logic in case that you haven't noticed, because:

decoder("did you see last night's episode?");
// Returns: "wrw blf hvv ozhg mrtsg'h vkrhlwv?"
decoder("wrw blf hvv ozhg mrtsg'h vkrhlwv?");
// Returns: "did you see last night's episode?"

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors