5
5
*/
6
6
7
7
function caesarCipher ( str , num ) {
8
+ if ( ! num ) throw new Error ( 'Missing argument: num' ) ;
9
+
8
10
const lowerCaseString = str . toLowerCase ( ) ;
9
11
const alphabets = 'abcdefghijklmnopqrstuvwxyz' . split ( '' ) ;
10
12
const totalAlphabets = alphabets . length ;
@@ -13,6 +15,12 @@ function caesarCipher(str, num) {
13
15
// handle large number, like 300 or -300
14
16
num %= totalAlphabets ;
15
17
18
+ const alphabetsMap = new Map ( ) ;
19
+
20
+ for ( const index in alphabets ) {
21
+ alphabetsMap [ alphabets [ index ] ] = index ;
22
+ }
23
+
16
24
for ( let index in lowerCaseString ) {
17
25
// get the current character
18
26
const currentCharacter = lowerCaseString [ index ] ;
@@ -24,7 +32,13 @@ function caesarCipher(str, num) {
24
32
}
25
33
26
34
// determine the new index
27
- const currentIndex = alphabets . indexOf ( currentCharacter ) ;
35
+ /**
36
+ * const currentIndex = alphabets.indexOf(currentCharacter);
37
+ *
38
+ * With indexOf complexity will be O(n*26)
39
+ * With Map complexity will be O(n).
40
+ */
41
+ const currentIndex = Number ( alphabetsMap [ currentCharacter ] ) ;
28
42
let newIndex = currentIndex + num ;
29
43
30
44
// if the index passes 25, restart from 0
0 commit comments