A.Lopez
A.Lopez

Reputation: 25

Caesars Cipher in JavaScript - Why does 'A' turn into '[' here?

I'm currently going through a FreeCodeCamp challenge that requests you to create a ROT13 cipher (a very simple cipher that shifts each letter to be the letter 13 letters ahead of it in a never-ending alphabet). My code is below:

function rot13(str) {
  let lettersRegex = /[A-Z]/;
  let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
  let charCodes = [];
  for(let i = 0; i < str.length; i++) {
    if(str.charAt(i).match(lettersRegex)) {
      charCodes.push(str.charCodeAt(i));
    } else {
      charCodes.push(str.charAt(i));
    }
  }
  let ret = '';
  console.log(`charCodes is currently ${charCodes}`);
  for(let i = 0; i < charCodes.length; i ++) {
    let temp = 0;
    if(lettersRegex.test(String.fromCharCode(charCodes[i]))) {
      if((alphabet.indexOf(String.fromCharCode(charCodes[i])) + 13) > alphabet.length) {
        temp = charCodes[i] + alphabet.indexOf(charCodes[i]) - 12;
      }
      else {
        temp = charCodes[i] + 13;
      }
      ret += String.fromCharCode(temp);
    } else {
      ret += charCodes[i];
    }
  }
  console.log(ret);
  return ret;
}
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.");
//THE QUICK BROWN FOX JUMPS OVER THE L[ZY DOG.

Basically, every letter but 'A' shifts to the correct answer after the cipher. What could be causing 'A' to turn into '[' instead of 'N' in this code?

Any comments or tips on my code would also be much appreciated.

Upvotes: 0

Views: 69

Answers (1)

Jeffrey Cash
Jeffrey Cash

Reputation: 1073

It's a simple fix, changing > to >= Don't forget that arrays are zero-indexed. if((alphabet.indexOf(String.fromCharCode(charCodes[i])) + 13) >= alphabet.length)

Upvotes: 2

Related Questions