Caesars Cipher Algorithm Question

Hi, I was wondering what’s going on with my code. Here’s the code:

function rot13(str) { // LBH QVQ VG!
  const abc = ['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'];

  let split = str.toLowerCase().split('');
  for (let i = 0; i < split.length; i++) {
    if (abc.indexOf(split[i]) <= 12) {
      split[i] = abc[i+13];
    } else if (abc.indexOf(split[i]) > 12) {
      split[i] = abc[i-13];
    } else if (abc.indexOf(split[i]) === -1) {
      split[i] = split[i];
  return split.join('');

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

and for some reason, the output is “ortw”. I’m extremely confused. Can anyone figure out why this is happening? Both why the output letters aren’t right and why there are only four characters outputted.

Walk through your code with the test case you are using and it should be obvious what is going on.

When i = 0, split[0] is ‘s’, so abc.indexOf(‘s’) is 18. so your if statement evaluates to false but the first else if (below) evaluates to true.

 else if (abc.indexOf(split[i]) > 12) {
      split[i] = abc[i-13];

Then you assign abc[0-13] to split[0]. abc[-13] is not a valid reference to an index in abc, so split[0] gets assigned the value undefined. Walk through the rest of the code for the various letters and you will see similar issues.

1 Like

Wow. Can’t believe I missed things so obvious, thank you once again Randell.