tried to create a function that does caesar cipher (alphabet shift by key
value). Wanted to do it in least lines possible (one line?). Was able to create a function:
const alphabet = "abcdefghijklmnopqrstuvwxyz".split('')
let regExp = /[a-zA-Z]/;
function cypher(input, key){
return input.split('').map((a) => (regExp.test(a)) ? alphabet[(alphabet.indexOf(a) + key) % alphabet.length] : a).join('')
}
then I figured out that I can use the same function to decipher the code, except with reversed alphabet
const alphabetReverse = alphabet.reverse();
function decypher(input, key){
return input.split('').map((a) => (regExp.test(a)) ? alphabetReverse[(alphabetReverse.indexOf(a) + key) % alphabetReverse.length] : a).join('')
}
then, I tried to do function that does both (if key < 0 it decyphers):
function cypher(input, key){
let alphabet = "abcdefghijklmnopqrstuvwxyz".split(''); // 26 long, 0 to 25
if(key < 0){
alphabet = alphabet.reverse();
key = -key;
}
return input.split('').map((a) => (regExp.test(a)) ? alphabet[(alphabet.indexOf(a) + key) % alphabet.length] : a).join('')
}
I cant figure out a way to do both-ways function in an elegant way like just one-way.
(Sorry if i’m missing something, this is more of an learning question, I’m really new to programming, like 2-3 weeks.
Tried creating both-ways function in one line, couldnt do it.
2
Answers
Instead of reversing the alphabet conditionally, make use of modular arithmetic (e.g. shifting backward 10 times is equal to shifting forward 16 times).
Maybe you mean something like
ROT13
https://hellodevworld.com/365-days-of-coding/rot13-cipher-javascript-solution
or you can use
XOR
encryption string with key like:Encrypt/decrypt string n JavaScript