Skip to content

Commit 20280c8

Browse files
committed
--update: replaced indexof with Map(), throw error on missing arguments
1 parent 479e925 commit 20280c8

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/_Classics_/caeser_cipher/index.js

+15-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
*/
66

77
function caesarCipher(str, num) {
8+
if (!num) throw new Error('Missing argument: num');
9+
810
const lowerCaseString = str.toLowerCase();
911
const alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
1012
const totalAlphabets = alphabets.length;
@@ -13,6 +15,12 @@ function caesarCipher(str, num) {
1315
// handle large number, like 300 or -300
1416
num %= totalAlphabets;
1517

18+
const alphabetsMap = new Map();
19+
20+
for (const index in alphabets) {
21+
alphabetsMap[alphabets[index]] = index;
22+
}
23+
1624
for (let index in lowerCaseString) {
1725
// get the current character
1826
const currentCharacter = lowerCaseString[index];
@@ -24,7 +32,13 @@ function caesarCipher(str, num) {
2432
}
2533

2634
// 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]);
2842
let newIndex = currentIndex + num;
2943

3044
// if the index passes 25, restart from 0

0 commit comments

Comments
 (0)