Created
August 21, 2014 23:37
-
-
Save alexhawkins/d8b64eaf920676b7d5e3 to your computer and use it in GitHub Desktop.
Basic Caesar Cipher and Decipher (send ciphered e-mails and texts with this simple code)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cipher = function(str, num) { | |
var code = 0, | |
cipher = ''; | |
for (var i = 0; i < str.length; i++) { | |
code = str.charCodeAt(i); | |
//check lowercase | |
if (code >= 97 && code <= 122) { | |
code += num; | |
//start at beginning of lowcase alphabet | |
if (code > 122) { | |
code -= 26; | |
} | |
} | |
//check uppercase | |
else if (code >= 65 && code <= 90) { | |
code += num; | |
//start at beginning of upcase alphabet | |
if (code > 90) { | |
code -= 26; | |
} | |
} | |
cipher += String.fromCharCode(code); | |
} | |
return cipher; | |
}; | |
var decipher = function(str, num) { | |
var code = 0, | |
decipher = ''; | |
for (var i = 0; i < str.length; i++) { | |
code = str.charCodeAt(i); | |
//check lowercase | |
if (code >= 97 && code <= 122) { | |
code -= num; | |
//start at beginning of lowcase alphabet | |
if (code < 97) { | |
code += 26; | |
} | |
} | |
//check uppercase | |
else if (code >= 65 && code <= 90) { | |
code -= num; | |
//start at beginning of upcase alphabet | |
if (code < 65) { | |
code += 26; | |
} | |
} | |
decipher += String.fromCharCode(code); | |
} | |
return decipher; | |
}; | |
//tests | |
console.log(cipher('The Fibonacci sequence is named after Fibonacci. His book Liber Abaci introduced the sequence to Western European mathematics, although the sequence had been described earlier in Indian mathematics.', 8)) | |
//Bpm Nqjwvikkq amycmvkm qa viuml inbmz Nqjwvikkq. Pqa jwws Tqjmz Ijikq qvbzwlckml bpm amycmvkm bw Emabmzv Mczwxmiv uibpmuibqka, itbpwcop bpm amycmvkm pil jmmv lmakzqjml miztqmz qv Qvlqiv uibpmuibqka. | |
console.log(cipher('Hello World!!!', 3)); //Khoor Zruog!!! | |
console.log(cipher('Biff Tannin', 12)); //Nurr Fmzzuz | |
console.log(cipher('Carmen San Diego', 8)); //Kizumv Aiv Lqmow | |
//test decipher | |
console.log(decipher('Bpm Nqjwvikkq amycmvkm qa viuml inbmz Nqjwvikkq. Pqa jwws Tqjmz Ijikq qvbzwlckml bpm amycmvkm bw Emabmzv Mczwxmiv uibpmuibqka, itbpwcop bpm amycmvkm pil jmmv lmakzqjml miztqmz qv Qvlqiv uibpmuibqka.', 8)); | |
//The Fibonacci sequence is named after Fibonacci. His book Liber Abaci introduced the sequence to Western European mathematics, although the sequence had been described earlier in Indian mathematics. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment