Created
December 23, 2021 12:51
-
-
Save el3um4s/998e8c16a587ccb65fb2567fc184c804 to your computer and use it in GitHub Desktop.
MEDIUM - 5 Ways To Code a Caesar Cipher - 10
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
const uppercase = () => | |
[...Array(26)].map((n, i) => `${String.fromCharCode(i + "A".charCodeAt())}`); | |
const lowercase = () => | |
[...Array(26)].map((n, i) => `${String.fromCharCode(i + "a".charCodeAt())}`); | |
const mod = (a, b) => { | |
const c = a % b; | |
return c < 0 ? c + b : c; | |
}; | |
const chiper = (array, shift) => { | |
const cipher = {}; | |
array.forEach((value, index) => { | |
cipher[value] = array[mod(index + shift, array.length)]; | |
}); | |
return cipher; | |
}; | |
const caesarChipher = (shift) => { | |
return { | |
...chiper(uppercase(), shift), | |
...chiper(lowercase(), shift), | |
}; | |
}; | |
const processCharacter = (cipher, character) => | |
cipher.hasOwnProperty(character) ? cipher[character] : character; | |
export default (text, shift) => { | |
const caesar = caesarChipher(shift); | |
return [...text].map((c) => processCharacter(caesar, c)).join(""); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment