File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments