function rot13(str) { // LBH QVQ VG!
function ceaser(num){
if (num < 65 || num > 90) {
return num;
}
if (num < 78){
return num + 13;
}
else {return num - 13;}
}
var phrase = "";
for (var i = 0; i < str.length; i++) {
var num = ceaser(str[i].charCodeAt());
var letter = String.fromCharCode(num);
phrase = phrase.concat(letter);
}
return phrase;
}
function rot13(str) { // LBH QVQ VG!
var newArr = str.toUpperCase().split('');
var z = "";
for (var i = 0; i < newArr.length; i++) {
z = newArr[i].charCodeAt();
if (z > 64 && z < 78) {
newArr[i] = String.fromCharCode(z + 13);
} else if (z > 77 && z < 91) {
newArr[i] = String.fromCharCode(z - 13);
}
}
return newArr.join('');
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Hi, guys just wanted also to share my solution, i even tried to explain my solution with comments, i hope it may be helpful in a way
/*
Function name: rot13Letter
Usage: {
Offsets letter by 13 steps to the right
For example:
A shoudl be N.
B should be O.
S should be F.
}
arguments: {
letter: {
The letter argument is the letter that will be offsetet by 13 steps to the right
}
}
*/
const rot13Letter = letter => {
//Check if letter is upper case
let isUpperCase = letter === letter.toUpperCase();
//Converts letter to lower case
letter = letter.toLowerCase();
//If the letter is actually not a letter return letter
if (!/[a-z]/.test(letter)) return letter;
//Findes the character code number of the letter and offsets it by 13
let letterCode = letter.charCodeAt() + 13;
//Finds the min char code number (char code number for letter a)
//Finds the max char code number (char code number for letter b)
let [min, max] = ["a".charCodeAt(), "z".charCodeAt()];;
//If the letter char code number is bigger then the max char code number do this
if (max < letterCode) {
//Subtract letter char code number with max char code number
letterCode -= max;
//Add leter char code number with min and offset it by 1
letterCode += min - 1;
}
//Transform the letter char code number to a letter
letter = String.fromCharCode(letterCode);
//Checks if the letter was uppercase
//if true change the letter to to upper case
//else return the lower case letter
letter = isUpperCase?letter.toUpperCase():letter;
return letter;
}
const rot13 = str => {
//Split the string to an array that contains all the words of the string
const words = str.split(/\s+/);
return (
//loops through all of the words
//When the loop has finnished returns the new words
words.map(
word => (
//Split the word to an array that contains all the letters of the word
//loops through all letters and converts every single letter with rot13Letter function
word.split("").map(
letter => rot13Letter(letter)
//Joins the array of letters to a word
).join("")
//When the loop has finnished it returns the word to the array
)
//Joins the array of words to a sentence
).join(" ")
);
};