Last active
January 13, 2018 00:34
-
-
Save hcz/c0d7a134dc3242ae491a74db94b1e0d5 to your computer and use it in GitHub Desktop.
Caesar's cipher, the shift 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
| const shift = (cypherShift, alphabet, messageChar) => { | |
| const charCode = (ch) => ch.toLowerCase().charCodeAt(0); | |
| let begin = charCode(alphabet.from); | |
| let end = charCode(alphabet.to); | |
| [begin, end] = (begin > end) ? [end, begin] : [begin, end]; | |
| const alphabetLength = end - begin; | |
| const shiftLength = cypherShift % alphabetLength; | |
| if (alphabetLength === 0) return messageChar; | |
| let result = charCode(messageChar); | |
| if (result > end || result < begin) return messageChar; | |
| result += shiftLength; | |
| if (result > end) { | |
| result = begin - 1 + result - end; | |
| } else if (result < begin) { | |
| result = end - 1 + begin - result; | |
| } | |
| return String.fromCharCode(result); | |
| } | |
| const cypher = (cypherShift, alphabet, message) => { | |
| const shiftCurry = (messageChar) => shift(cypherShift, alphabet, messageChar); | |
| return message | |
| .toLowerCase() | |
| .split('') | |
| .map(shiftCurry) | |
| .join(''); | |
| } | |
| const decypher = (cypherShift, alphabet, message) => { | |
| return cypher(-cypherShift, alphabet, message); | |
| } | |
| const CYPHER_SHIFT = 3; | |
| const message = 'Good sense is the most equally distributed'; | |
| const A = 'a', Z = 'z'; | |
| const myCaesarCypher = cypher(CYPHER_SHIFT, {from: A, to: Z}, message); | |
| console.log(message); | |
| console.log(myCaesarCypher); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment