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.
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 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?
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.
All in all my initial idea was to make this code faster and smaller. I fully understand the readability issues which arise from that.
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.
Anyway thank you everyone for your time and ideas!
I learned a lot playing with the cipher code.
I think it’s time I went on to the cash register project.