Skip to content

Instantly share code, notes, and snippets.

@el3um4s
Created December 23, 2021 12:51
Show Gist options
  • Save el3um4s/998e8c16a587ccb65fb2567fc184c804 to your computer and use it in GitHub Desktop.
Save el3um4s/998e8c16a587ccb65fb2567fc184c804 to your computer and use it in GitHub Desktop.
MEDIUM - 5 Ways To Code a Caesar Cipher - 10
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