Skip to content

Commit b0a49fd

Browse files
Merge pull request #30 from Polyneue/enhancement/#14-add-caesars-cipher
Adding the Caesar's Cipher algorithm
2 parents 2d2f407 + 2fd39c8 commit b0a49fd

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Ciphers/caesarsCipher.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Caesar's Cipher - also known as the ROT13 Cipher is when
3+
* a letter is replaced by the one that is 13 spaces away
4+
* from it in the alphabet. If the letter is in the first half
5+
* of the alphabet we add 13, if it's in the latter half we
6+
* subtract 13 from the character code value.
7+
*/
8+
9+
/**
10+
* Decrypt a ROT13 cipher
11+
* @param {String} str - string to be decrypted
12+
* @return {String} decrypted string
13+
*/
14+
function rot13(str) {
15+
let response = [];
16+
let strLength = str.length;
17+
18+
for (let i =0; i < strLength; i++) {
19+
const char = str.charCodeAt(i);
20+
21+
switch(true) {
22+
// Check for non-letter characters
23+
case char < 65 || (char > 90 && char < 97) || char > 122:
24+
response.push(str.charAt(i));
25+
break;
26+
// Letters from the second half of the alphabet
27+
case (char > 77 && char <= 90 ) || (char > 109 && char <= 122):
28+
response.push(String.fromCharCode(str.charCodeAt(i) - 13));
29+
break;
30+
// Letters from the first half of the alphabet
31+
default:
32+
response.push(String.fromCharCode(str.charCodeAt(i) + 13));
33+
}
34+
}
35+
return response.join('');
36+
}
37+
38+
39+
// Caesars Cipher Example
40+
const encryptedString = 'Uryyb Jbeyq';
41+
const decryptedString = rot13(encryptedString);
42+
43+
console.log(decryptedString); // Hello World

0 commit comments

Comments
 (0)