Last active
December 20, 2016 11:46
-
-
Save michael-mafi/53a2c273dc5533ef0152cc498fbc8516 to your computer and use it in GitHub Desktop.
ceasars cipher
This file contains hidden or 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
| function rot13(str) { | |
| return str.split('').map.call(str, function(char) { | |
| x = char.charCodeAt(0); | |
| if (x < 65 || x > 90) { | |
| return String.fromCharCode(x); | |
| } | |
| else if (x < 78) { | |
| return String.fromCharCode(x + 13); | |
| } | |
| return String.fromCharCode(x - 13); | |
| }).join(''); | |
| } | |
| /////////////////////////////////////////////////////////////////////////////////another way | |
| // Solution with Regular expression and Array of ASCII character codes | |
| function rot13(str) { | |
| var rotCharArray = []; | |
| var regEx = /[A-Z]/ ; | |
| str = str.split(""); | |
| for (var x in str) { | |
| if (regEx.test(str[x])) { | |
| // A more general approach | |
| // possible because of modular arithmetic | |
| // and cyclic nature of rot13 transform | |
| rotCharArray.push((str[x].charCodeAt() - 65 + 13) % 26 + 65); | |
| } else { | |
| rotCharArray.push(str[x].charCodeAt()); | |
| } | |
| } | |
| str = String.fromCharCode.apply(String, rotCharArray); | |
| return str; | |
| } | |
| // Change the inputs below to test | |
| rot13("LBH QVQ VG!"); | |
| /////////////////////////////////////////////////////////////////////////////////another way | |
| function rot13(str) { // LBH QVQ VG! | |
| return str.replace(/[A-Z]/g, (L) => String.fromCharCode(65 + (L.charCodeAt(0) - 65 + 13) % 26)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment