JavaScript Algorithms and Data Structures Projects: Caesars Cipher - Don't know what's wrong with this code

JavaScript Algorithms and Data Structures Projects: Caesars Cipher - Don't know what's wrong with this code
0

Tell us what’s happening:
Hello there, I tried solving this project with the code below but I’m stuck as it is returning “SRRR POQR PZC”. I don’t know what’s wrong with this code. Please help me out. Thanks!

Your code so far


function rot13(str) { // LBH QVQ VG!
var newStr = str.split('');
var alphabets = String.fromCharCode(...Array(91).keys()).slice(65);

var aArr = alphabets.split('');

for(var i = 0; i < newStr.length - 1; i++) {
  if(aArr.includes(newStr[i])) {
    if(((aArr.indexOf(newStr[i])) + 13) > 26) {
      var index = aArr.indexOf(newStr[i]) - 13;
      newStr[i] = aArr[index];
    }
    newStr[i] = aArr[aArr.indexOf(newStr[i]) + 13];
  } else newStr[i] = newStr[i];
}
console.log(newStr);
console.log(aArr.indexOf(newStr[0]));
console.log(newStr.join(''));
return newStr.join('');
}

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




Your browser information:

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

Challenge: Caesars Cipher

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher

You have three problems:

for (var i = 0; i < newStr.length - 1; i++) {

You are not iterating all the way through the array with the above for loop condition.

if(((aArr.indexOf(newStr[i])) + 13) > 26) {

Are you sure the number should be 26 here? Arrays are zero-indexed.

newStr[i] = aArr[aArr.indexOf(newStr[i]) + 13];

The line above will always execute, which will negate the effect of the previous if statement’s

Hint: This line should be contained as a code block of a special statement.

1 Like

Thank you so much for this quick reponse.
I have changed my code as per your directions and it successfully cleared all test cases.
Here’s my updated code:

function rot13(str) { // LBH QVQ VG!
  var newStr = str.split('');
  var alphabets = String.fromCharCode(...Array(91).keys()).slice(65);

  var aArr = alphabets.split('');

  for(var i = 0; i < newStr.length; i++) {
    if(aArr.includes(newStr[i])) {
      if(((aArr.indexOf(newStr[i])) + 13) > 25) {
        var index = aArr.indexOf(newStr[i]) - 13;
        newStr[i] = aArr[index];
      }
      else if(((aArr.indexOf(newStr[i])) + 13) <= 25) {
        newStr[i] = aArr[aArr.indexOf(newStr[i]) + 13];
      }
    }
  }
  console.log(newStr);
  console.log(aArr.indexOf(newStr[0]));
  console.log(newStr.join(''));
  return newStr.join('');
}

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



rot13("SERR CVMMN!");

Great job!

Do you really need an else if here? There is a simpler statement that would work.

1 Like

Oh yeah! Thanks for pointing out!