After trying (and failing) to code a Caesar Cipher assignment for the Odin Project exercise, I finally caved in and looked up the answer. However, I do not quite understand it.
I am seeking an explanation of each line does and why it works. The code I copied has some brief descriptions of what each line does, but I still don't understand how it all works.
const caesar = function (str, amount) {
// Wrap the amount
if (amount < 0) {
return caesar(str, amount + 26);
}
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90) {
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
}
// Lowercase letters
else if (code >= 97 && code <= 122) {
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
}
// Append
output += c;
}
// All done!
return output;
};
The first if-statement:
if (amount < 0) {
return caesar(str, amount + 26)
}
Makes sure that the shifting amount is 0 and above by calling itself until it is. Then the following line loops through all the characters in the entire string.
for (var i = 0; i < str.length; i++) {
For every character it checks if its a letter using something called a regex (Google for more information)
if (c.match(/[a-z]/i)) {
The line
var code = str.charCodeAt(i);
Gets the number representing the character at position "i" in the string. The number is the way the computer represents letters and other characters. Upper- and lowercase characters have two completely different numbers associated with them. That is what the two following if-statements is for. I will explain the one for lowercase letters, you should be able to see how the uppercase one works as well.
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
It starts by subtracting 65 from the number. This is because the first lowercase letter "a" has a value of 65. After that it shifts the result by "amount". The %-sign might seem weird. But all it does is divide the two sides and returning the "rest", the residual number. For example if we write:
5 % 2
It is equal to 1. This is done to "loop" the number and keep it between 0 and 26. After that it adds back the 65 and turns the number back to a character. The last line:
output += c;
Adds the character to the resulting string. Hope this helped you out!