Last active
August 29, 2015 14:15
-
-
Save tsprates/4ea682df787beb845f70 to your computer and use it in GitHub Desktop.
Caesar Cipher
This file contains hidden or 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
/** | |
* Caesar cipher. | |
* | |
* @link http://en.wikipedia.org/wiki/Caesar_cipher | |
* @param {string} msg | |
* @param {number} shift | |
* @return {string} | |
*/ | |
function caesarCipher(msg, shift) { | |
var result = "", | |
regexp = /^[a-z]$/i, | |
a = 'a'.charCodeAt(0), | |
ch; | |
for (var i = 0, len = msg.length; i < len; i++) { | |
ch = msg.charAt(i); | |
result += (regexp.test(ch)) | |
? String.fromCharCode((msg.charCodeAt(i) + shift - a + 26) % 26 + a); | |
: ch; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment