Javascript: Caesar’s Cipher

Free Code Camp: This is the final exercise of the Basic Algorithm Scripting exercises. The exercise calls for a function that takes a string input, and shifts the ASCII value of each letter or character by 13 places. For example, the letter “Z” equals 90 according to the ASCII table Therefore by shifting the character 13 places, the ASCII value becomes either 103 or 77 (“g”or “M” respectively). For this algorithm to work, an input of “SERR CVMMN!” should return “FREE CODE CAMP.”

The tricky aspect of this exercise is that spaces and non letter characters should remain the same, and that whatever is output must remain an upper case letter or characters within the ASCII numeric values of 65 to 90.

Below is my solution:

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

var ourArray = [];

var updatedArray = [];

var largest = 0;
for (var i = 0; i < str.length; i++) {

if (str.charCodeAt(i) >= 78) { ourArray.push(str.charCodeAt(i) – 13);
// return String.fromCharCode(splitString.charCodeAt(i));
}

else if (str.charCodeAt(i) < 64) {

ourArray.push(str.charCodeAt(i));
}

else {ourArray.push(str.charCodeAt(i) + 13);

}
}

// return ‘ ‘.charCodeAt(0);

// return String.fromCharCode(ourArray);

for (var j = 0; j < str.length; j++) {
updatedArray.push( String.fromCharCode(ourArray[j]) );
}
// return ourArray;
return updatedArray.join(”);
}

// Change the inputs below to test
rot13(“SERR CVMMN!”);