Caesar's Cipher: code decodes correctly, but it still fails the tests? [SOLVED]

Caesar's Cipher: code decodes correctly, but it still fails the tests? [SOLVED]
0.0 0

#1

Hi, I am struggling to work out why this code is failing the tests for Caeser’s Cipher, as it seems to produce the correct decoded answer:

var charCode = "";
var decodedArray = [];

function rot13(str) {
  // loop through the provided string
  for (i = 0; i < str.length; i++) {
    // check if each character is a letter
    if (str[i].match(/[a-z]/i)) {
      //convert the letter to its character code and subtract 13 to decode it 
      charCode = str.charCodeAt(i) - 13;
      // if the decoded character is lower than A (65) make the subtraction loop back to Z (90)
      if (charCode < 65) {
        charCode = charCode + 26;
      }  
      // convert the character code back into a string, and push the decoded letter to 'decodedArray' 
     decodedArray.push(String.fromCharCode(charCode));
    }
    // in the loop, if a character is found which is not a letter, push it directly to 'decodedArray'
    else {
     decodedArray.push(str[i]);
    }
  }  
  // once the loop has completed, join decodedArray back into a string 
  str = decodedArray.join("");
  return str;
}

// Change the inputs below to test
rot13("LBH QVQ VG!");

Does anyone know what I might be doing wrong?


#2

You are using global variables.

Global variables persist after function calls have completed, so we have to be very careful about modifying globals in functions. Your code relies on charCode being an empty string and decodedArray being an empty array when the function is called, but after rot13 has been executed they are no longer empty. This means that your function will only work once.


#3

aha! great, thank you for the explanation :slight_smile:

putting the variables inside my function fixed the problem.


#4

Also, you can’t be adding 26 when the requirement is to ROT13. It’s either +13 when your charcode is between 65 and 77, and -13 when it’s between 78 and 90.
Or maybe you can? I’d have to try your code but I’m on the iPad.


#5

in the above code I’m adding 26 to (str.charCodeAt(i) - 13) so it finds its way to the right place eventually… I just wrote it in the order which I thought it through in my head, but your suggestion is probably more elegant!


#6

Yeah I see what you did, hence my unsure answer. That’s pretty sweet if it works. Simpler than mine in fact.