Skip to content

Instantly share code, notes, and snippets.

@roniceyemeli
Last active September 29, 2022 11:29
Show Gist options
  • Save roniceyemeli/a4fe97fc9253b3ce56b5f189a6f8ba41 to your computer and use it in GitHub Desktop.
Save roniceyemeli/a4fe97fc9253b3ce56b5f189a6f8ba41 to your computer and use it in GitHub Desktop.
Caesars Cipher encryption
function rot13(str) {
let key = 13;
let lowerAlphabet = 'abcdefghijklmnopqrstuvwxyz'
let upperAlphabet = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase();
let lowerAlphabetArr = lowerAlphabet.split('');
lowerAlphabetArr.push(...lowerAlphabetArr.splice(0,key))
let alphabetPushed = lowerAlphabetArr.join('')
let alphabetPushedUp = alphabetPushed.toUpperCase();
let strEncoded = [];
for(let i = 0; i<str.length; i++){
if(alphabetPushed[lowerAlphabet.indexOf(str[i])] !== undefined){
strEncoded.push(alphabetPushed[lowerAlphabet.indexOf(str[i])])
} else if(alphabetPushedUp[upperAlphabet.indexOf(str[i])] !== undefined){
strEncoded.push(alphabetPushedUp[upperAlphabet.indexOf(str[i])])
} else{
strEncoded.push(str[i])
}
}
return strEncoded.join('')
}
// rot13("SERR PBQR PNZC"); will return FREE CODE CAMP
function rot13(encodedStr) {
var lookup = {
'A': 'N','B': 'O','C': 'P','D': 'Q',
'E': 'R','F': 'S','G': 'T','H': 'U',
'I': 'V','J': 'W','K': 'X','L': 'Y',
'M': 'Z','N': 'A','O': 'B','P': 'C',
'Q': 'D','R': 'E','S': 'F','T': 'G',
'U': 'H','V': 'I','W': 'J','X': 'K',
'Y': 'L','Z': 'M'
};
var codeArr = encodedStr.split(""); // String to Array
var decodedArr = []; // Your Result goes here
// Only change code below this line
decodedArr = codeArr.map(function(letter) {
if(lookup.hasOwnProperty(letter)) {
letter = lookup[letter];
}
return letter;
});
// Only change code above this line
return decodedArr.join(""); // Array to String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment