Last active
August 30, 2015 01:22
-
-
Save loickreitmann/dd0f452e924f0343a490 to your computer and use it in GitHub Desktop.
Javascript version of Caesar shift
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
function crypt(message, shiftText, isDecrypt) { | |
'use strict'; | |
return caesarShift(message.toUpperCase(), getShift(shiftText, isDecrypt)); | |
} | |
function getShift(shiftText, isDecrypt) { | |
var shift; | |
if (isNaN(shiftText) && !/^-?\d+$/.test(shift)) { | |
console.log("Shift is not an integer"); | |
return 0; | |
} | |
shift = parseInt(shiftText, 10); | |
shift = (shift < 0) ? -1 * shift : shift; | |
shift = (shift >= 26) ? shift % 26 : shift; | |
if (isDecrypt) { | |
shift = (26 - shift) % 26; | |
} | |
return shift; | |
} | |
function caesarShift(text, shift) { | |
var result = "", | |
i, | |
c, | |
aCode = "A".charCodeAt(0), | |
zCode = "Z".charCodeAt(0); | |
for (i = 0; i < text.length; i++) { | |
c = text.charCodeAt(i); | |
if (c >= aCode && c <= zCode) { | |
// encrypt or decrypt | |
result += String.fromCharCode((c - aCode + shift) % 26 + aCode); | |
} else { | |
// copy | |
result += text.charAt(i); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment