Skip to content

Instantly share code, notes, and snippets.

@zenius
Last active September 15, 2020 12:22
Show Gist options
  • Save zenius/c3fa480503facb68188cc6163279a233 to your computer and use it in GitHub Desktop.
Save zenius/c3fa480503facb68188cc6163279a233 to your computer and use it in GitHub Desktop.
freecodecamp Caesars Cipher Project Solution
//'A'.charCodeAt() === 65
// 'N'.charCodeAt() === 78
#Solution No.1
function rot13(str) {
let result = '';
for(let i = 0; i < str.length; i++) {
let char = str[i];
if(/[A-Z]/.test(char)) {
let value = char.charCodeAt();
// if value < 78, move forward by 13
// else move backward by 13
value = value < 78 ? (value + 13): (value -13)
result += String.fromCharCode(value);
} else {
result += char;
}
}
return result;
}
#Solution No.2:
function rot13(str) {
let result = '';
for(let i = 0; i < str.length; i++) {
let char = str[i];
if(/[A-Z]/.test(char)) {
const value = (char.charCodeAt()- 65 + 13) % 26 + 65;
} else {
result += char;
}
}
return result;
}
Problem Link:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment