-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaesarCipher.js
31 lines (25 loc) · 930 Bytes
/
caesarCipher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function caesarCipher(str, num) {
num = num % 26;
let lowerCaseString = str.toLowerCase();
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
let newString = '';
for (let i = 0; i < lowerCaseString.length; i++) {
let currentLetter = lowerCaseString[i];
if (currentLetter === ' ') {
newString += currentLetter;
continue;
}
let currentIndex = alphabet.indexOf(currentLetter);
let newIndex = currentIndex + num;
if (newIndex > 25) newIndex = newIndex - 26;
if (newIndex < 0) newIndex = 26 + newIndex;
if (str[i] === str[i].toUpperCase()) {
newString += alphabet[newIndex].toUpperCase();
}
else newString += alphabet[newIndex];
}
return newString;
}
caesarCipher('Zoo Keeper', 2); // Bqq Mggrgt
caesarCipher('Javascript', -900); // Bqq Mggrgt
caesarCipher('Dhimas Akbar', 27); // Eijnbt Blcbs