Last active
December 27, 2019 02:26
-
-
Save JaymesKat/79e569574b52d6e9329c2446e7c6b456 to your computer and use it in GitHub Desktop.
One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount. A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on. Write a function which takes a RO…
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
function createAlphabetArr(){ | |
const first = 'A'.charCodeAt(); | |
const second = 'Z'.charCodeAt(); | |
let alphabet = []; | |
for(let code = first; code <= second; code++) { | |
alphabet.push(String.fromCharCode(code)) | |
} | |
return alphabet; | |
} | |
const alphabet = createAlphabetArr(); | |
function rot13(str) { // LBH QVQ VG! | |
const chars = str.split(''); | |
let ciphedText = []; | |
let i = 0; | |
while(i < chars.length){ | |
if(chars[i].match(/[A-Z]/i)){ | |
ciphedText.push(cipher(chars[i])); | |
} else { | |
ciphedText.push(chars[i]) | |
} | |
i++; | |
} | |
return ciphedText.join(''); | |
} | |
function cipher(letter){ | |
const currentPosition = alphabet.indexOf(letter); | |
const shiftedPosition = currentPosition < 13 ? currentPosition + 13 : (currentPosition + 13 - 25) - 1; | |
return alphabet[shiftedPosition]; | |
} | |
// Should return THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. | |
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment