Last active
November 13, 2018 11:36
-
-
Save akinjide/9803674a4b1b47c377d5fb0b9e7db0a0 to your computer and use it in GitHub Desktop.
one of the simplest and most widely known encryption techniques.
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
/** | |
* 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