Caesars Cipher! Help me complete it

Caesars Cipher! Help me complete it
0.0 0

#1

Tell us what’s happening:
I already feel a lot stupid because of the code I have written and I know there exists a really better way to make this challenge work but since I wrote it, I would love if someone can just help me make it work the right way. I will still give it few more hours but I need help with few things… If you understand my approach then please help me figure out few things missing in this thing but I don’t think it’s worth your time. Thanks!

Your code so far

function rot13(str) { // LBH QVQ VG!
  var myArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M','N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  var arr = [];
  var ar = [];
  var bab = [];
  for (var i = 0; i < str.length; i++) {
    arr.push(myArr.indexOf(str[i]));
    if (arr[i] >= 13){
      ar.push(arr[i] - 13);
    } else {
      ar.push(arr[i] + 13);
    } 
    bab.push(myArr[ar[i]]); 
    }
  return bab.join('').replace(/M/g, " ");
}
// Change the inputs below to test
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");

Your browser information:

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

Link to the challenge:


#2

The problem with your current logic is that you if arr[i] < 13, then your else code block executes.

ar.push(arr[i] + 13);

Since any character which is not an uppercase letter will result in arr[i] being -1 (because of the following line), you are end up adding 13 to -1 which results in bab[i] having an “M” instead of the non-letter character it should have.

arr.push(myArr.indexOf(str[i]));

One way to remedy this, is to have the first if statement check if arr[i] is equal to -1. If it is, then you can push whatever you want to ar, but then push str[i] into bab to capture the actual non-letter character. This will force you to create an else which will have the remaining logic inside it’s code block (see below).

// the code below will be nested inside the else statement described above.		 
 if (arr[i] >= 13) {
   ar.push(arr[i] - 13);
 }
 else {
   ar.push(arr[i] + 13);
 }
 bab.push(myArr[ar[i]]);