Skip to content

Adding the Caesar's Cipher algorithm #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 16, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Ciphers/caesarsCipher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Caesar's Cipher - also known as the ROT13 Cipher is when
* a letter is replaced by the one that is 13 spaces away
* from it in the alphabet. If the letter is in the first half
* of the alphabet we add 13, if it's in the latter half we
* subtract 13 from the character code value.
*/

/**
* Decrypt a ROT13 cipher
* @param {String} str - string to be decrypted
* @return {String} decrypted string
*/
function rot13(str) {
let response = [];
let strLength = str.length;

for (let i =0; i < strLength; i++) {
const char = str.charCodeAt(i);

switch(true) {
// Check for non-letter characters
case char < 65 || (char > 90 && char < 97) || char > 122:
response.push(str.charAt(i));
break;
// Letters from the second half of the alphabet
case (char > 77 && char <= 90 ) || (char > 109 && char <= 122):
response.push(String.fromCharCode(str.charCodeAt(i) - 13));
break;
// Letters from the first half of the alphabet
default:
response.push(String.fromCharCode(str.charCodeAt(i) + 13));
}
}
return response.join('');
}


// Caesars Cipher Example
const encryptedString = 'Uryyb Jbeyq';
const decryptedString = rot13(encryptedString);

console.log(decryptedString); // Hello World