|
1 | 1 | function caeserCipher(str, num) {
|
2 | 2 | const lowerCaseString = str.toLowerCase();
|
3 | 3 | const alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
|
| 4 | + const totalAlphabets = alphabets.length; |
4 | 5 | let result = '';
|
5 | 6 |
|
6 |
| - for (let char of lowerCaseString) { |
7 |
| - const current = char; |
8 |
| - if (current === ' ') { |
9 |
| - result += current; |
| 7 | + for (let index in lowerCaseString) { |
| 8 | + // get the current character |
| 9 | + const currentCharacter = lowerCaseString[index]; |
| 10 | + |
| 11 | + // if character is space, add it to the result and continue to next |
| 12 | + if (currentCharacter === ' ') { |
| 13 | + result += currentCharacter; |
10 | 14 | continue;
|
11 | 15 | }
|
12 | 16 |
|
13 |
| - const currentIndex = alphabets.indexOf(current); |
| 17 | + // determine the new index |
| 18 | + const currentIndex = alphabets.indexOf(currentCharacter); |
14 | 19 | let newIndex = currentIndex + num;
|
15 | 20 |
|
16 |
| - if (newIndex > alphabets.length - 1) { |
17 |
| - newIndex -= alphabets.length; |
| 21 | + // if the index passes 25, restart from 0 |
| 22 | + if (newIndex > totalAlphabets - 1) { |
| 23 | + newIndex -= totalAlphabets; |
| 24 | + } |
| 25 | + |
| 26 | + // check if the character in original string was upper case |
| 27 | + if (str[index] === alphabets[currentIndex].toUpperCase()) { |
| 28 | + result += alphabets[newIndex].toUpperCase(); |
18 | 29 | }
|
19 | 30 | result += alphabets[newIndex];
|
20 | 31 | }
|
21 | 32 | return result;
|
22 | 33 | }
|
23 | 34 |
|
24 |
| -console.log(caeserCipher('abcz', 2)); |
| 35 | +console.log(caeserCipher('abCz', 2)); |
0 commit comments