One thing you might look into is how you can make use of ‘modular arithmetic’ to make the ‘rotational’ part of the cipher more efficient. It’s the same kind of math that can be used to calculate an arrival time even when a 24-hour clock ‘resets’ to 0 after midnight…
I did mine comparing on letters rather than on their charCode. That makes it easier to read and you don’t have ‘magic’ numbers (who knows the charCodes of the set off the top of their head?).
When you use a RegEx to check for letters and non-letters, you can do away with the long condition in your first if statement.
Like @geligelu said: try to make the comparisons more efficient.
Re 2: if (str[i].match(/[A-Z]/)) { /* it's a letter */ }
Some good advice above here. I would add that you are doing a lot of duplicate calls to convert your string to and from charCode. Whenever you repeat yourself a lot in your code you should pause and think about if it’s really necessary.
You might want to think about using a variable to store the converted value in this case.
Wow, I did use the regex to find out if it’s a letter and I did use the test ( < ‘N’) to find out if I needed to add or subtract 13, but it never occurred to me to do just a replace. Great idea.
I am burning my brain trying to solve this one. I copy and paste my code after a lot of thinking. I think it should work the way it is… but I am almost sure that I am not knowing how to deal with the charcode. I tried to find some cheatcode or something so I could analyze the charcode better.
I am felling stucked in this one now. Just because I couldn’t make the charcode loop or create some equation on it.
If it is the only bad part in my code, please help me understand the charset or how to think about that.
Thanks a lot!
function rot13(str) { // LBH QVQ VG!
function replacer(X){
return String.fromCharCode(X.charCodeAt(0));
}
return str.replace(/[A-Z]/g, replacer);
}