Skip to content

Instantly share code, notes, and snippets.

@SerhiiLihus
Created January 5, 2016 09:08
Show Gist options
  • Save SerhiiLihus/c3a935bbe711bec37135 to your computer and use it in GitHub Desktop.
Save SerhiiLihus/c3a935bbe711bec37135 to your computer and use it in GitHub Desktop.
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.
// Bonfire: Caesars Cipher
// Author: @serhiilihus
// Challenge: http://www.freecodecamp.com/challenges/bonfire-caesars-cipher#?solution=function%20rot13(encodedStr)%20%7B%0A%20%20var%20codeArr%20%3D%20encodedStr.split(%22%22)%3B%20%20%2F%2F%20String%20to%20Array%0A%20%20var%20decodedArr%20%3D%20%5B%5D%2C%20newletterCode%3B%20%2F%2F%20Your%20Result%20goes%20here%0A%20%20%2F%2F%20Only%20change%20code%20below%20this%20line%0A%20%20codeArr.forEach(function(letter)%7B%0A%20%20%20%20%20%20%20newletterCode%20%3D%20(letter.charCodeAt()%20%3C%2065%20%7C%7C%20letter.charCodeAt()%20%3E%2090)%3F%20letter.charCodeAt()%20%3A%20(letter.charCodeAt()%20%2B%2013%20%3E%2090%20)%3F%20letter.charCodeAt()%20-%2013%20%3A%20letter.charCodeAt()%20%2B%2013%3B%0A%20%20%20%20%20%20%20decodedArr.push(String.fromCharCode(newletterCode))%3B%0A%20%20%7D)%3B%0A%20%20%2F%2F%20Only%20change%20code%20above%20this%20line%0A%20%20return%20decodedArr.join(%22%22)%3B%20%2F%2F%20Array%20to%20String%0A%7D%0A%0A%2F%2F%20Change%20the%20inputs%20below%20to%20test%0Arot13(%22SERR%20PBQR%20PNZC%22)%3B%0A
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function rot13(encodedStr) {
var codeArr = encodedStr.split(""); // String to Array
var decodedArr = [], newletterCode; // Your Result goes here
// Only change code below this line
codeArr.forEach(function(letter){
newletterCode = (letter.charCodeAt() < 65 || letter.charCodeAt() > 90)? letter.charCodeAt() : (letter.charCodeAt() + 13 > 90 )? letter.charCodeAt() - 13 : letter.charCodeAt() + 13;
decodedArr.push(String.fromCharCode(newletterCode));
});
// Only change code above this line
return decodedArr.join(""); // Array to String
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment