Skip to content

Instantly share code, notes, and snippets.

@jsmayo
Last active July 26, 2017 22:21
Show Gist options
  • Save jsmayo/bf2e8b51cdb726809ca93831cbe9de30 to your computer and use it in GitHub Desktop.
Save jsmayo/bf2e8b51cdb726809ca93831cbe9de30 to your computer and use it in GitHub Desktop.
Caesars Cipher
One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.
A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.
A ROT13 encoded string takes user input and returns a decoded strings in the following
* All letters will be uppercase.
* Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.
* Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
String.prototype.charCodeAt()
Syntax: str.charCodeAt(index)
Parameters: index value of the string it’s called on.
Returns: A number representing the UTF-16 code unit value of the character at the given index; NaN if index is out of range.
* Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding.
String.fromCharCode()
Syntax: String.fromCharCode(num1, num2, .. )
Returns: The string generated from the unicode values that were passed in.
* Static method of String.
* Returns a string, NOT a string object!
SOLN:
function rot13(str) { // LBH QVQ VG!
var newStr = "";
for ( var i = 0; i < str.length; i++ ) {
char = str.charCodeAt(i);
if ( char < 65 || char > 90 ) {
char = char;
}
else {
char += 13;
if ( char > 90 ) {
char = ( char - 90 ) + 64;
}
}
newStr += String.fromCharCode(char);
}
return newStr;
}
TESTS:
rot13("SERR PBQR PNZC") should decode to "FREE CODE CAMP"
rot13("SERR CVMMN!") should decode to "FREE PIZZA!"
rot13("SERR YBIR?") should decode to "FREE LOVE?"
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.") should decode to "THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment