-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar-cipher.js
43 lines (34 loc) · 1.14 KB
/
caesar-cipher.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
38
39
40
41
42
43
/**
* @param {string} cleartext
* @param {number} k the alphabet rotation factor
* @return {string} the encrypted string
*/
const alphabetLength = 26;
const alphabetLowerCase = [
...Array(alphabetLength)
].map((_, idx) => String.fromCharCode(idx + 'a'.charCodeAt()));
function caesarCipher(s, k) {
k = k % alphabetLength;
s = s.toLowerCase();
let newString = '';
for(let i = 0; i < s.length; i++) {
let currentLetter = s[i];
if(/\s/.test(currentLetter)) {
newString += currentLetter;
continue;
}
let newIdx = (alphabetLowerCase.indexOf(currentLetter)) + k;
if(newIdx > 25) {
newIdx = newIdx - alphabetLength;
}
if(newIdx < 0) {
newIdx = newIdx + alphabetLength;
}
if(s[i] === s[i].toUpperCase()) {
newString += alphabetLowerCase[newIdx].toUpperCase();
} else {
newString += alphabetLowerCase[newIdx];
}
}
return newString;
}