Ceasar cipher - Here's my code - spoiler alert

Can’t seem to find the FreeCodeCamp Bot that has answers and explanations, so I’m just going to post my code.

function rot13(str) { // LBH QVQ VG!
var newString = ‘’;

for (var i =0; i<str.length; i++){
var n = str.charCodeAt(i);
var r = (n + 13 +65)%26 + 65;

if (/[A-Z]/.test(str[i])){
     newString += (String.fromCharCode(r));
    } else {
  newString += str[i];
}   

}
return newString;
}

2 Likes

We can provide answers, but what is your question?

This is what I came up with…

function rot13(str) { // LBH QVQ VG!

  function ceaser(num){
    if (num < 65 || num > 90) {
      return num;
    }
    if (num < 78){
      return num + 13;
    }
    else {return num - 13;}
  }
  
  var phrase = "";
  for (var i = 0; i < str.length; i++) {
    var num = ceaser(str[i].charCodeAt());
    var letter = String.fromCharCode(num);
    phrase = phrase.concat(letter);
  }
  return phrase;
}

Here’s mine :slight_smile:

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

Here’s mine 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");

It actualy very interested to see difference, who measuring speed and how it possible to do for JS scripts?
here my code

> function rot13(str) {
    var nStr="";
	var fStr="";
	for(var i=0;i<=str.length-1;i++)
	{
	nStr=str.codePointAt(i);
		if (nStr>=65&&nStr<=77)
		{
		nStr=String.fromCharCode(nStr+13);
		}else if (nStr>=78&&nStr<=91){
		nStr=String.fromCharCode(nStr-13);
		}else{
		nStr=String.fromCharCode(nStr);
		}
    fStr+=nStr;
	}
  return fStr;
}

Here’s my code. It’s a bit long but it also does the job.

function rot13(str) { // LBH QVQ VG!
var obj = {
A: “N”, B: “O”, C: “P”, D: “Q”, E: “R”, F: “S”, G: “T”, H: “U”, I: “V”, J: “W”, K: “X”, L: “Y”, M: “Z”, N: “A”, O: “B”, P: “C”, Q: “D”, R: “E”, S: “F”, T: “G”, U: “H”, V: “I”, W: “J”, X: “K”, Y: “L”, Z: “M”};
var fare = str.split(’’);
var fada = [];
var i = 0;
while (i < fare.length) {
if (fare[i] === “!” || fare[i] === “?” || fare[i] === “.” || fare[i] === " "){
switch (fare[i]) {
case “!”:
fada.push(fare[i]);
break;
case “?”:
fada.push(fare[i]);
break;
case “.”:
fada.push(fare[i]);
break;
case " ":
fada.push(fare[i]);
break;
}
}

  else {
      fada.push(obj[fare[i]]);
}
i++;  

}

return fada.join(’’);
}

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

Hi, guys just wanted also to share my solution, i even tried to explain my solution with comments, i hope it may be helpful in a way :smiley:

/*
Function name: rot13Letter

Usage: {
    Offsets letter by 13 steps to the right 
    
    For example: 
        A shoudl be N.
        B should be O.
        S should be F.
}    

arguments: {
    letter: {
        The letter argument is the letter that will be offsetet by 13 steps to the right
    }
}
*/
const rot13Letter = letter => {
    //Check if letter is upper case
    let isUpperCase = letter === letter.toUpperCase();

    //Converts letter to lower case
    letter = letter.toLowerCase();

    //If the letter is actually not a letter return letter
    if (!/[a-z]/.test(letter)) return letter;

    //Findes the character code number of the letter and offsets it by 13
    let letterCode = letter.charCodeAt() + 13;

    //Finds the min char code number (char code number for letter a)
    //Finds the max char code number (char code number for letter b)
    let [min, max] = ["a".charCodeAt(), "z".charCodeAt()];;

    //If the letter char code number is bigger then the max char code number do this
    if (max < letterCode) {

        //Subtract letter char code number with max char code number
        letterCode -= max;

        //Add leter char code number with min and offset it by 1
        letterCode += min - 1;
    }

    //Transform the letter char code number to a letter
    letter = String.fromCharCode(letterCode);

    //Checks if the letter was uppercase 
    //if true change the letter to to upper case 
    //else return the lower case letter
    letter = isUpperCase?letter.toUpperCase():letter;

    return letter;
}

const rot13 = str => {
    //Split the string to an array that contains all the words of the string
    const words = str.split(/\s+/);

    return (
        
        //loops through all of the words
        //When the loop has finnished returns the new words 
        words.map(
            word => (
                
                //Split the word to an array that contains all the letters of the word
                //loops through all letters and converts every single letter with rot13Letter function
                word.split("").map(
                    letter => rot13Letter(letter)

                //Joins the array of letters to a word
                ).join("")
                //When the loop has finnished it returns the word to the array
            )
        
        //Joins the array of words to a sentence
        ).join(" ")
    );
};