Ceasars Cipher, Improvements and Suggestions

Hi all, can anyone make a comment on my code on this topic Ceasars Chipher?

Here’s the code:

function rot13(str) { // LBH QVQ VG!
var newStr = [];
for (var i = 0; i < str.length; i++){
if (str.charCodeAt(i) < 65) {
newStr.push(str.charCodeAt(i));
}else if (str.charCodeAt(i) > 64 && str.charCodeAt(i) < 91){
if ((str.charCodeAt(i) + 13) > 90){
newStr.push(((str.charCodeAt(i) + 13) - 90) + 64);
}else {
newStr.push(str.charCodeAt(i) + 13);
}
}
}
return String.fromCharCode.apply(null, newStr);
}

// Change the inputs below to test
rot13(“SERR PBQR PNZC”);

Please, thank you all!!!

1 Like

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");

Here’s my version


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.

Thank you All! This helps a lot.

Here my version:
function rot13(str) { // LBH QVQ VG!
var decoded = ‘’;
for(var i = 0; i < str.length; i++) {
if (str[i].match(/\w/g)) {
if (str[i].charCodeAt(0)<=77) {
decoded= decoded + String.fromCharCode(str[i].charCodeAt(0) + 13);
}
else {
decoded= decoded + String.fromCharCode((str[i].charCodeAt(0) % 13) + 65);
}
}
else {
decoded= decoded + str[i];
}
}
return decoded;
}