Skip to content

Commit c376de5

Browse files
committed
--fix: edge case of upper case alphabet
1 parent 12f9ba2 commit c376de5

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/_Classics_/caeser_cipher/index.js

+19-8
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,35 @@
11
function caeserCipher(str, num) {
22
const lowerCaseString = str.toLowerCase();
33
const alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
4+
const totalAlphabets = alphabets.length;
45
let result = '';
56

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;
1014
continue;
1115
}
1216

13-
const currentIndex = alphabets.indexOf(current);
17+
// determine the new index
18+
const currentIndex = alphabets.indexOf(currentCharacter);
1419
let newIndex = currentIndex + num;
1520

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();
1829
}
1930
result += alphabets[newIndex];
2031
}
2132
return result;
2233
}
2334

24-
console.log(caeserCipher('abcz', 2));
35+
console.log(caeserCipher('abCz', 2));

0 commit comments

Comments
 (0)