File tree 1 file changed +12
-4
lines changed
src/_Classics_/caeser_cipher
1 file changed +12
-4
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Most simplest encryption scheme. Read more: [http://practicalcryptography.com/ciphers/caesar-cipher/]
3
+ * @param {String } str
4
+ * @param {Number } num
5
+ */
6
+
1
7
function caeserCipher ( str , num ) {
2
8
const lowerCaseString = str . toLowerCase ( ) ;
3
9
const alphabets = 'abcdefghijklmnopqrstuvwxyz' . split ( '' ) ;
4
10
const totalAlphabets = alphabets . length ;
5
11
let result = '' ;
6
12
13
+ // handle large number, like 300 or -300
14
+ num %= totalAlphabets ;
15
+
7
16
for ( let index in lowerCaseString ) {
8
17
// get the current character
9
18
const currentCharacter = lowerCaseString [ index ] ;
@@ -28,12 +37,11 @@ function caeserCipher(str, num) {
28
37
}
29
38
30
39
// check if the character in original string was upper case
31
- if ( str [ index ] === alphabets [ currentIndex ] . toUpperCase ( ) ) {
40
+ if ( str [ index ] === str [ index ] . toUpperCase ( ) ) {
32
41
result += alphabets [ newIndex ] . toUpperCase ( ) ;
42
+ } else {
43
+ result += alphabets [ newIndex ] ;
33
44
}
34
- result += alphabets [ newIndex ] ;
35
45
}
36
46
return result ;
37
47
}
38
-
39
- console . log ( caeserCipher ( 'abCz' , 2 ) ) ;
You can’t perform that action at this time.
0 commit comments