Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active August 29, 2015 14:15
Show Gist options
  • Save tsprates/4ea682df787beb845f70 to your computer and use it in GitHub Desktop.
Save tsprates/4ea682df787beb845f70 to your computer and use it in GitHub Desktop.
Caesar Cipher
/**
* 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