JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Caesars Cipher
I’m total new at coding and this is mine version of Caesars Cipher X)
Really struggling with JS, but hope that I’ll do it better in future)
If you have advises or just comments, I’ll be glad to read them)

Code:

function rot13(str) {
  str = str.toUpperCase();
  let res = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i].charCodeAt() >= 65)  {
      let q = str[i].charCodeAt() + 13;
      if (q <= 90 && q > 65) {
      res.push(String.fromCharCode(q));
      } else {
        res.push(String.fromCharCode(65 + (q - 90) - 1));
      } 
    } else {
      res.push(str[i])
    }
  }
  return res.join('');
}

rot13("SERR PBQR PNZC");

Challenge: JavaScript Algorithms and Data Structures Projects - Caesars Cipher

Link to the challenge:

It’s good to start with some self-reflection on the code. What was easy, what was hard? What do you think is good in code, what do you think could be improved? Some specific places that are hard to read/understand?

Hm, maybe hard side is logic of code - cant figure out fast enough, but when I do (or look at other ppl solutions) I see that it was really easy and basic logic.
I think good side of this specific code is easy to understand (except “q” variable, I just forgot to rename it XD). Bad side - its to big X)

Its hard to explain for me my problems with code.
I just hope that more practice will improve my code skill)

Don’t be mistaken - these easy and basic looking solutions wasn’t like that from the start, unless somebody encountered similar problem countless times before. When function is working as intended that’s good time to take another look at it. At that point it’s easier to see what is necessarily required, what might be not needed at all or could be made simpler.

You are right, q could have better name. There’s couple details like that. Ie.

  • 13, 65, 90 could be replaced with named constants, it could make clearer what are they.
  • str[i].charCodeAt() is used twice, line after line, this could be also replaced with variable.
  • Declared variables in this function with let, could be declared with const, as they aren’t reassigned anywhere.
  • If you take a look at the two conditions:
if (str[i].charCodeAt() >= 65)  {
      let q = str[i].charCodeAt() + 13;
      if (q <= 90 && q > 65) {

Is it possible for q to not be higher than 65?

1 Like

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