-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.js
More file actions
49 lines (33 loc) · 1.21 KB
/
caesar_cipher.js
File metadata and controls
49 lines (33 loc) · 1.21 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
/*
Move each character of the string by provided number of position and return new string
E.g:
caesarCipher("car", 2)
output: ect
caesarCipher("lal", -1)
output: kzk
caesarCipher("lal", 30)
output: pep
*/
function caesarCipher(str, num) {
const alphabets = 'abcdefghijklmnopqrstuvwxyz';
const alphabetsArr = alphabets.split("");
let newStr = '';
num = num % alphabetsArr.length;
for (let i=0; i <= str.length; i++) {
const currentChar = str[i];
if (currentChar === ' ') {
newStr += currentChar;
continue;
}
if (alphabetsArr.indexOf(currentChar) !== -1) {
const currentIndex = alphabetsArr.indexOf(currentChar);
let newIndex = currentIndex + num;
if (newIndex >= alphabetsArr.length) newIndex = newIndex - alphabetsArr.length;
if (newIndex < 0) newIndex = alphabetsArr.length + newIndex;
console.log( 'current Index', currentIndex, 'New Index', newIndex);
newStr += alphabetsArr[newIndex];
}
}
return newStr
}
caesarCipher('lalz', 4)