Caesars Cipher. Refactoring

So I took your last comment into account and also tried to check if it was possible to get rid of the “if” statement. It looks like I managed to do it. :smiley:
Here’s my solution:

function rot13(str) {
  let endStr = "";
  for (const value of str) {
    endStr = value.toLowerCase() != value.toUpperCase() ? endStr + String.fromCharCode((str.charCodeAt(str.indexOf(value)) % 26) + 65) : endStr + value;
  }
  return endStr;
}
console.log(rot13("SERR YBIR?"));

In this case we don’t even need the extra var for str.charCodeAt(str.indexOf(value))

I admire your tenacity…

Can you drop the + everywhere and just use += instead of = u think?

Yeah I forgot to delete the “+” signs before posting the code here.

function rot13(str) {
  let endStr = "";
  for (const value of str) {
    endStr += value.toLowerCase() != value.toUpperCase() ? String.fromCharCode((str.charCodeAt(str.indexOf(value)) % 26) + 65) : value;
  }
  return endStr;
}
console.log(rot13("GUNAX LBH UONE1FG!!!"));

So there isn’t left anything else to “optimize” for this particular method, I think… Or is there?

i was wondering about that…is it better to use extra variables? it does seem to save memory adlers way?

I see. Could you tell me, please, considering serious projects, as a general rule, do you opt for memory saving or readability? Or maybe such issues are not usually present?

I prefer readability myself… Plus as you are learning you may come back to this and forget what the heck you were doing here…

1 Like

A regular for loop is obviously better here, I used the for of since I was suggested to do so (and it was also a new experience for me anyway).
Considering the reduce method - thank you for the idea. I will need to do some research on implementing it here.

Regex was omitted from latest versions of the code for variety. :slightly_smiling_face:

All in all my initial idea was to make this code faster and smaller. I fully understand the readability issues which arise from that.

Thank you very much!

I also meant to suggest that you can play with a map function as well if you like (to produce the final string).
I agree with Randell on all his points about using variables and making the code more readable in the process.

1 Like

Anyway thank you everyone for your time and ideas! :hugs:
I learned a lot playing with the cipher code.
I think it’s time I went on to the cash register project.

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