Skip to content

Instantly share code, notes, and snippets.

@GitSquared
Created January 16, 2020 21:34
Show Gist options
  • Save GitSquared/bdc58d72c4984270533d4aece17c8f50 to your computer and use it in GitHub Desktop.
Save GitSquared/bdc58d72c4984270533d4aece17c8f50 to your computer and use it in GitHub Desktop.
JS Caesar Cypher
const letters = 'abcdefghijklmnopqrstuvwxyz';
let circleBackAlphabet = new Proxy({ letters }, {
get: (obj, index) => {
let ltrs = obj.letters;
while(index > ltrs.length-1) {
index = index - ltrs.length;
}
return ltrs[index];
}
});
function caesarCypher(str, x) {
str = str.toLowerCase();
return [...str].map(c => {
let i = letters.indexOf(c);
if (i === -1) return c;
return circleBackAlphabet[i+x];
}).join('');
}
// ----
console.log(' 5 =>', circleBackAlphabet[5]);
console.log(' 25 =>', circleBackAlphabet[25]);
console.log(' 37 =>', circleBackAlphabet[37]);
console.log('284 =>', circleBackAlphabet[284]);
console.log('Hello world! (x = 2) =>', caesarCypher('Hello world!', 2));
console.log('Lorem ipsum dolor sit amet (x = 735) =>', caesarCypher('Lorem ipsum dolor sit amet', 735));
console.log('!1349;:#€ (x = 4) =>', caesarCypher('!1349;:#€', 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment