The Solution: Step-by-Step
for (let i=0; i < str.length; i++)
This is a for loop that will run along, starting at 0, for as long as the variable i
is less than the string's length (number of letter in this case).
let asciiNumber
You can have an array with all the letters of the alphabet, or you can use the ascii table
. Ascii stands for American Standard Code for Information Interchange.
str[i].charCodeAt();
This piece of code will use the ascii table to convert the letter in the position i
to its numerical equivalent.
Example: If the word is "GO" then str[0]
is "G", with a charCodeAt()
of "71". On the next loop, str[1]
is "O", with a charCodeAt()
of "79".
if (asciiNumber >= 65 && asciiNumber <= 77) {encoded += String.fromCharCode(asciiNumber + 13);}
The alphabet in the ascii table runs from 65 to 90. Per this exercise, in order to decode the message, each letter is shifted forward 13 positions.
Example: Using our previous example, the letter 'G' has a charcode of "71". If we add 71 + 13 we get 84. Using fromCharCode(84)
we get the letter "T"
If we do the same with the letter "O" we get that 79 + 13 = 92. Using fromCharCode(92)
we do not get a letter, but a '\'. this is the reason I have added the next part of the code.
else if (asciiNumber >= 78 && asciiNumber <= 90) {encoded += String.fromCharCode(asciiNumber - 13); }
With the numerical equivalent of the alpphabet running from 65 to 90, if we want to shift 13 positions forward from 90 we need to adjust the formula. Luckily this case is easy enoght, instead of adding we subtract.
Solving the problem we had with the letter "O", if instead of adding we do 79 - 13 = 66. Using fromCharCode(66)
we get the letter "B"
else {encoded += str[i];}
What happens in the cases where we have spaces, numbers, lowercase or others? We just add them to the solution as they are. No changes.
return encoded;
The solution returned for the example used will be "TB".