forked from shams-nahid/Algorithms-In-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesarCipher.js
38 lines (27 loc) · 882 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
32
33
34
35
36
37
const caesarCipher = (mainString, num, cb) => {
console.log(mainString);
let newString = '', currentIndex, newIndex;
let myString = mainString.toLowerCase().split('');
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
let index = 0;
myString.map((val) => {
if (!alphabet.includes(val)) {
newString += val;
index++;
return;
}
currentIndex = alphabet.indexOf(val);
newIndex = (currentIndex + num) % 26;
if (newIndex < 0) newIndex += 26;
if (mainString.charAt(index) == val.toUpperCase()) {
newString += alphabet[newIndex].toUpperCase();
} else {
newString += alphabet[newIndex];
}
index ++;
});
cb(newString);
};
caesarCipher('Bqq Mggrgt', -55, (result) => {
console.log('Result is: ' + result);
});