Skip to content

Instantly share code, notes, and snippets.

@AndrewYatzkan
Last active June 11, 2018 21:48
Show Gist options
  • Save AndrewYatzkan/472f3510bb35dbfa17ae2e8160e7f90e to your computer and use it in GitHub Desktop.
Save AndrewYatzkan/472f3510bb35dbfa17ae2e8160e7f90e to your computer and use it in GitHub Desktop.
Caesar Cipher / Character Shifter
// Shifts an alphabetic string (e.i. 'a' --> 'b')
// The 'str' argument is the string to pass in
// 'n' is the number of characters that should be shifted
// Supports shifting either forwards or backwards any amount
// Example:
// Input: shift('Ebiil, Tloia!', 3);
// Expected Output: "Hello, World!"
// Takes into account capital letters, lowercase letters, ignores non-alphabetic characters
function shift(str, n) {
var shifted = '';
n %= 26;
for (var i = 0; i < str.length; i++) {
let code = str[i].charCodeAt();
let capital = (code > 64 && code < 91) ? true : false;
if (code < (capital?65:97) || code > (capital?90:122) || n == 0) {
shifted += str[i];
continue;
}
if (n > 0) {
if (code > (capital?90:122)-n) {
code = n + code - 26;
} else {
code += n;
}
} else {
if (code < (capital?65:97)-n) {
code = code + n + 26;
} else {
code += n;
}
}
shifted += String.fromCharCode(code);
}
return shifted;
}
// Below is the same function in prototype form aka 'string'.shift(n) as opposed to shift('string', n)
String.prototype.shift = function(n) {
var shifted = '';
n %= 26;
for (var i = 0; i < this.length; i++) {
let code = this[i].charCodeAt();
let capital = (code > 64 && code < 91) ? true : false;
if (code < (capital?65:97) || code > (capital?90:122) || n == 0) {
shifted += this[i];
continue;
}
if (n > 0) {
if (code > (capital?90:122)-n) {
code = n + code - 26;
} else {
code += n;
}
} else {
if (code < (capital?65:97)-n) {
code = code + n + 26;
} else {
code += n;
}
}
shifted += String.fromCharCode(code);
}
return shifted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment