Created
January 16, 2020 21:34
-
-
Save GitSquared/bdc58d72c4984270533d4aece17c8f50 to your computer and use it in GitHub Desktop.
JS Caesar Cypher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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