There’s many ways to complete the challenge. I’ve also did the almost same. Have a look at my code:
function rot13(str) { // LBH QVQ VG!
var newArr = str.toUpperCase().split('');
var z = "";
for (var i = 0; i < newArr.length; i++) {
z = newArr[i].charCodeAt();
if (z > 64 && z < 78) {
newArr[i] = String.fromCharCode(z + 13);
} else if (z > 77 && z < 91) {
newArr[i] = String.fromCharCode(z - 13);
}
}
return newArr.join('');
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
function rot13(str) { // LBH QVQ VG!
function decode(val){
// check if character is between A-Z
if (val>='A' && val<='Z') {
return val.charCodeAt() > (64+13) ? String.fromCharCode(val.charCodeAt()-13) : String.fromCharCode(val.charCodeAt()+13);
} else {
// not A-Z; so return original character
return val;
}
}
return str.split('').map( decode ).join('');
}
It’s basically a single line calling a “decode” function.
return str.split('').map( decode ).join('');
each letter is passed to the decode function, and then I do a direct >= or <= comparison against the letter.
if outside the range of A…Z, return the original character
if inside the range, check if it’s A + 13th char, and subtract 13. Otherwise, add 13
return the character, then join the whole array of characters to return a string value.