Skip to content

Instantly share code, notes, and snippets.

@EnzoDiazDev
Last active August 15, 2021 20:25
Show Gist options
  • Save EnzoDiazDev/1d8b13992ab737a60ca1313c60e0f3bf to your computer and use it in GitHub Desktop.
Save EnzoDiazDev/1d8b13992ab737a60ca1313c60e0f3bf to your computer and use it in GitHub Desktop.
Vigenère Cipher using typescript in a funcional way
type CipherEquation = (Xi:number, Ki:number, L:number) => number;
const encoder = (Xi:number, Ki:number, L:number) => (Xi + Ki) % L;
const decoder = (Ci:number, Ki:number, L:number) => (Ci - Ki) >= 0 ? (Ci - Ki) % L : (Ci - Ki + L) % L;
function repeat_key(to_length:number, key):string {
if(key.length < to_length) {
return repeat_key(to_length, key.repeat(2));
} else {
return key.slice(0, to_length + 1);
}
}
type VigenereCipher = (str:string, equation:CipherEquation) => string;
function vigenere_cipher(alphabet:string, key:string):VigenereCipher {
const L = alphabet.length;
return function(str, equation) {
const repeated_key = repeat_key(str.length, key);
return str
.split("")
.map((C, i) => {
const Ci = alphabet.indexOf(C);
const K = repeated_key[i];
const Ki = alphabet.indexOf(K);
if(Ci === -1) return C;
const Ri = equation(Ci, Ki, L);
return alphabet[Ri];
})
.join("");
};
}
//Redhat client
const redhat_cipher = vigenere_cipher("abcdefghijklmnopqrstuvwxyz", "novyuspxqa");
const redhat_encode = (message:string) => redhat_cipher(message, encoder);
const redhat_decode = (message:string) => redhat_cipher(message, decoder);
redhat_encode("hello hacker!"); // usgji wxskrf!
redhat_decode("usgji wxskrf!"); // hello hacker!
//IBM client
const ibm_cipher = vigenere_cipher("abcdefghijklmnñopqrstuvwxyz", "gtjmdglsonpvbtm");
const ibm_encode = (message:string) => ibm_cipher(message, encoder);
const ibm_decode = (message:string) => ibm_cipher(message, decoder);
ibm_encode("hello thinker!"); // nxtwr ezwzzzs!
ibm_decode("nxtwr ezwzzzs!"); // hello thinker!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment