Caesars Cipher v252 SOLVED

Tell us what’s happening:
Can’t figure out how to get the array or string from numbers back to letters. Ideas?

Your code so far

function rot13(str) { 
  var nArr = [];
  var number;
  var letter;
  for (i=0; i<str.length; i++){
  if (65 <= str.charCodeAt(i) && str.charCodeAt(i) <= 90){ //if it's between A-Z convert it
    number = str.charCodeAt(i)+13;  //convert + 13
    if (number > 90) {   //if the number is above 90 (Z) minus 26 to bring it down to range 65-90 (A-Z)
       number = number - 26;
    }
    letter = String.fromCharCode(number); //convert to letter
    nArr.push(letter); //push letters to array
   }
    else nArr.push(str[i]);
  }
  nArr = nArr.join('');
  return nArr;
}

// Change the inputs below to test
rot13("SERR CVMMN!");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/caesars-cipher

nArr is an array and fromCharCode needs a string. I tried using .toString then fromCharCode but that didn’t work.

  • fromCharCode() takes a number(s) as argument(s), not a string.
  • If you want to convert a whole array to a single string, you will want to use join().

See updated code, I can convert everything fine. Now I need to make it if the number is over 90 (Z) then loop it back to A (65).

That’s the logical bit that takes many people a little while to figure out.

That’s the last part, right? What about another if statement? If the number is over 77 then do something special to it? If statements are so sloppy tho, must be a cleaner way.

There’s nothing inherently wrong with if statements. They’re super useful. If you find yourself with an elaborate system of if/else statements, then you might want to restructure your logic.

Code updated. The function is converting things that aren’t between 65 and 90, like ? and !. I can’t figure out why, ideas?

I know why it seems like this should work, but you actually need to do
if (65 <= str.charCodeAt(i) && str.charCodeAt(i) <= 90)

You still won’t get the exact right solution. Only your letters will show up in your final result. Can you figure out why?

I get “FREE4PIZZA10” as a result…I’m not sure how this is happening. Space is ASCII 32 and ! is ASCII 33, which are not in the range I specified.

What is your current code?

I had an i in the push method so it was pushing the position of the space (4) and the ! (10). Current code works, I just need it to push the spaces, ! and ? through.

Current code works! Just needed to push the value at i if the first if statement didn’t work. Thanks man.

Congratulations!