Caesars Cipher_What am I missing?

Hello! This is my first post in this forum. I just started to code a couple of months ago. I hope someone can help me. In this chalange (Caesars Cipher) I can’t figure out the last step… I found all the others algorithms pretty easy but I am really stuck on this one.

Here is my code for now:

function rot13(str) { // LBH QVQ VG!
  var arr = [];
  for (i=0; i< str.length; i++) {
  	if (str.charCodeAt(i) > 64 && str.charCodeAt(i) < 91) {
  		if (str.charCodeAt(i) -13 < 65) {
  			arr.push(str.charCodeAt(i) -13 + 26);
  		} else {
  			arr.push(str.charCodeAt(i) -13);
  		}
  	} else {
  		arr.push(str.charCodeAt(i));
  	}
  }
  console.log(arr);
  
  //how to do this last step...?
  //var finalStr = String.fromCharCode(arr???);
  return finalStr;
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

Thank you!

Well… I think I’ve just solved it! (Finally!) But probably there is a really better way.

function rot13(str) { // LBH QVQ VG!
  var arr = [];
  for (i=0; i< str.length; i++) {
  	if (str.charCodeAt(i) > 64 && str.charCodeAt(i) < 91) {
  		if (str.charCodeAt(i) -13 < 65) {
  			arr.push(str.charCodeAt(i) -13 + 26);
  		} else {
  			arr.push(str.charCodeAt(i) -13);
  		}
  	} else {
  		arr.push(str.charCodeAt(i));
  	}
  }
  
  var newArr = [];
  for (i=0; i< arr.length; i++) {
  	newArr.push(String.fromCharCode(arr[i]));
  }
  
  var finalStr = newArr.join("");
  return finalStr;
}

rot13("SERR PBQR PNZC");
  1. Maybe instead of subtracting 13 and adding 26 you can just add 13 in line 6.

  2. Then you could simplify by removing the if - else from line 5 to 8.

  3. Does this below work for you?

             var arr = [];
               	for (i=0; i< str.length; i++)
      {
               	if (str.charCodeAt(i) < 65 || str.charCodeAt(i) > 90) 
               		{
         arr.push(str.charCodeAt(i)); // Return un-converted 
               		} else if (str.charCodeAt(i) < 78)
               		{
               			arr.push(str.charCodeAt(i) + 13); //Simply add 13
               		} else 
               	{
               		arr.push(str.charCodeAt(i) - 13); //Simply remove 13
               	}
               }
               
               var newArr = [];
               for (i=0; i< arr.length; i++) {
               	newArr.push(String.fromCharCode(arr[i]));
               }
               
               var finalStr = newArr.join("");
               return finalStr;

Oh, yes! That second point simplifies it a bit! :slight_smile: Thank you for your answer!