Skip to content

Instantly share code, notes, and snippets.

@patrickodacre
Last active July 12, 2016 03:03
Show Gist options
  • Save patrickodacre/f002d63c8df952489796d57e4fb2414c to your computer and use it in GitHub Desktop.
Save patrickodacre/f002d63c8df952489796d57e4fb2414c to your computer and use it in GitHub Desktop.
Solution for Free Code Camp's basic algorithm challenge 16
function rot13(str) { // LBH QVQ VG!
var codeArr = str.split(''); // arrays are fun to work with.
var decodes = codeArr.reduce(function (tempArr, currentValue, currentIndex) {
var charCode = str.charCodeAt(currentIndex);
// Pass through any non-alpha characters.
if (currentValue === '' || (charCode < 65 || charCode > 90 )) {
tempArr.push(currentValue);
return tempArr;
} else if (charCode < 78) {
tempArr.push(String.fromCharCode(charCode + 13)); // subtracting 13 would take us past A
} else {
tempArr.push(String.fromCharCode(charCode - 13)); // adding 13 would take us past Z
}
return tempArr;
}, []);
var result = decodes.join(''); // make it a string again.
return result;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
rot13("SERR CVMMN!");
rot13("SERR YBIR?");
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment