I have been following the FreeCodeCamp, and I am done with the basic algorithm challenges. The last one (CaesarsCipher) troubled me a bit, though I had done a similar one without much problem in C, for CS50 course.
Finally I made it work, but at the moment I am self-critical about "How?" I made it work and the quality of my code. I found the basic solution provided quite hard to understand and it looks way advanced than my code. I am posting my code here with the hope of receiving some feedback on it and finding out if am I doing something wrong/should be concerned about improving quality before moving on to new topics and challenges. (such as writing style or the functions i use/ the way I handle the problem)
function rot13(str) { // LBH QVQ VG!
//defining an isAlpha function to skip the non alpha chars
var isAlpha = function(char){
return typeof char==="string" && char.length == 1 && char <= "Z" && char >="A";
};
//two empty arrays two use later
var shifted = [];
var decoded= [];
/*transform the encoded chars to ascii numbers then shift by 13
and copy the decoded char to another array
*/
for(var i = 0; i < str.length; i++){
if(isAlpha(str[i]) && str[i].charCodeAt() < 78) {
shifted[i] = str[i].charCodeAt()+13;
decoded.push(String.fromCharCode(shifted[i]));
}
else if(isAlpha(str[i]) && str[i].charCodeAt() >= 78){
shifted[i] = str[i].charCodeAt() - 13;
decoded.push(String.fromCharCode(shifted[i]));
}
else{
decoded.push(str[i]);
}
}
//lastly merge the decoded chars into a string
var last = decoded.join("");
return last;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");