Skip to content

Instantly share code, notes, and snippets.

@akinjide

akinjide/caesarCipher.js

Last active Nov 13, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.