Skip to content

Instantly share code, notes, and snippets.

@EnzoDiazDev
Created August 14, 2021 20:16
Show Gist options
  • Save EnzoDiazDev/6462f6f4d917e12aa2a4ba1820716835 to your computer and use it in GitHub Desktop.
Save EnzoDiazDev/6462f6f4d917e12aa2a4ba1820716835 to your computer and use it in GitHub Desktop.
vigenere with functions p4
const key = "password";
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const L = alphabet.length;
type cipher_equation = (Xi:number, Ki:number, L:number) => number;
const encode_char = (Xi:number, Ki:number, L:number) => (Xi + Ki) % L;
const decode_char = (Ci:number, Ki:number, L:number) => (Ci - Ki) >= 0 ? (Ci - Ki) % L : (Ci - Ki + L) % L;
function repeat_key(length:number):string {
let new_key = key;
while(new_key.length < length){
new_key = new_key.repeat(2);
}
return new_key.slice(0, length + 1);
}
function vigenere_cipher(str:string, equation:cipher_equation):string {
const key = repeat_key(str.length);
return str
.split("")
.map((C, i) => {
const Ci = alphabet.indexOf(C);
const K = key[i];
const Ki = alphabet.indexOf(K);
if(Ci === -1) return C;
const Ri = equation(Ci, Ki, L);
return alphabet[Ri];
})
.join("");
}
const encode = (str:string) => vigenere_cipher(str, encode_char);
const decode = (str:string) => vigenere_cipher(str, decode_char);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment