JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Tell us what’s happening:

I have done a similar solution doing the harvard cs50 version but I am having trouble understanding why this solution does not work. Looks like it breaks right after a non alpha char.

E.g. rot13(“SERR PBQR PNZC”) :

console.log(temp) shows correct ascii values:
[ 70, 82, 69, 69, 67, 79, 68, 69, 67, 65, 77, 80 ] //CORRECT ASCII

but ans.push(String.fromCharCode(temp[i]) results in:
[ ‘F’, ‘R’, ‘E’, ‘E’, ’ ', ‘\u0000’, ‘\u0000’, ‘\u0000’, ‘\u0000’, ’ ', ‘\u0000’, ‘\u0000’, ‘\u0000’, ‘\u0000’ ]

showing the regex and temp is working as intended but something is wrong with the ans.push statement. any thoughts? (Also understand I need a join statement aswell but I want to fix this before finishing fully)

EDIT: As I am writing this draft I now see the error. I ended up fixing it to work and pass all tests. But I will still post in the hope someone can benefit from it.

As the loop runs it checks if the string char is alphabetical, if it is not alpha, it automatically adds string[i] to ans. However, the next iteration the loop runs that is alpha, it pushes the char value into temp correctly BUT since there is no update to temp[arr] when there are special chars, it is continuously adding an out of bounds temp[i] value causing it to only add undefined values after a special char.

Your code so far

const isAlpha = str => /^[A-Z]*$/.test(str);

function rot13(str) {
const key = 13;
 let temp = [];
 let ans = [];
  for (let i = 0; i < str.length; i++) {
    if (isAlpha(str[i]) === false) {
      ans.push(str[i])
    } else {
    temp.push(((((str.codePointAt(i)) - 65) + key) % 26) + 65);
    console.log(temp);
    ans.push(String.fromCharCode(temp[i]));
      }
  }
  console.log(ans)
}

rot13("SERR PBQR PNZC")

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

JavaScript Algorithms and Data Structures Projects - Caesars Cipher

The white space is getting translated into ROT13.

Happy coding

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.