Skip to content

Instantly share code, notes, and snippets.

@akinjide
Last active November 13, 2018 11:36
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 akinjide/9803674a4b1b47c377d5fb0b9e7db0a0 to your computer and use it in GitHub Desktop.
Save akinjide/9803674a4b1b47c377d5fb0b9e7db0a0 to your computer and use it in GitHub Desktop.
one of the simplest and most widely known encryption techniques.
/**
* Returns the result of having each alphabetic letter of the given text string shifted forward
* by the given amount, with wraparound. Case is preserved, and non-letters are unchanged.
*
* i.e.
*
* - caesarShift({ text: "abz", shift: 0 }) = "abz".
* - caesarShift({ text: "abz", shift: 1 }) = "bca".
* - caesarShift({ text: "abz", shift: 25 }) = "zay".
* - caesarShift({ text: "THe 123 !@#$", shift: 13 }) = "GUr 123 !@#$".
**/
const caesarShift = ({ text, shift }) => {
let result = '';
for (var i = 0; i < text.length; i++) {
let c = text.charCodeAt(i);
if (65 <= c && c <= 90) {
result += String.fromCharCode((c - 65 + shift) % 26 + 65); // Uppercase
} else if (97 <= c && c <= 122) {
result += String.fromCharCode((c - 97 + shift) % 26 + 97); // Lowercase
} else {
result += text.charAt(i); // Copy
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment