Skip to content

Instantly share code, notes, and snippets.

@loickreitmann
Last active August 30, 2015 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loickreitmann/dd0f452e924f0343a490 to your computer and use it in GitHub Desktop.
Save loickreitmann/dd0f452e924f0343a490 to your computer and use it in GitHub Desktop.
Javascript version of Caesar shift
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