Skip to content

Commit 110a2da

Browse files
committed
Caesar cipher algorithm
1 parent 8d8d177 commit 110a2da

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Algorithm/caesarCipher.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function caesarCipher(str, num) {
2+
num = num % 26;
3+
let lowerCaseString = str.toLowerCase();
4+
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
5+
let newString = '';
6+
7+
for (let i = 0; i < lowerCaseString.length; i++) {
8+
let currentLetter = lowerCaseString[i];
9+
if (currentLetter === ' ') {
10+
newString += currentLetter;
11+
continue;
12+
}
13+
let currentIndex = alphabet.indexOf(currentLetter);
14+
let newIndex = currentIndex + num;
15+
if (newIndex > 25) newIndex = newIndex - 26;
16+
if (newIndex < 0) newIndex = 26 + newIndex;
17+
if (str[i] === str[i].toUpperCase()) {
18+
newString += alphabet[newIndex].toUpperCase();
19+
}
20+
else newString += alphabet[newIndex];
21+
}
22+
23+
return newString;
24+
}
25+
26+
caesarCipher('Zoo Keeper', 2); // Bqq Mggrgt
27+
28+
caesarCipher('Javascript', -900); // Bqq Mggrgt
29+
30+
caesarCipher('Dhimas Akbar', 27); // Eijnbt Blcbs
31+

0 commit comments

Comments
 (0)