From 2fd39c88ff07727124cc4b55f5c713b81f44942e Mon Sep 17 00:00:00 2001 From: Ed Mendoza Date: Sun, 15 Oct 2017 17:07:44 -0400 Subject: [PATCH] Adding the Caesar's Cipher algorithm --- Ciphers/caesarsCipher.js | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Ciphers/caesarsCipher.js diff --git a/Ciphers/caesarsCipher.js b/Ciphers/caesarsCipher.js new file mode 100644 index 0000000000..af6369c6d4 --- /dev/null +++ b/Ciphers/caesarsCipher.js @@ -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 \ No newline at end of file