-
Notifications
You must be signed in to change notification settings - Fork 0
/
CaesarCipher.js
38 lines (30 loc) · 873 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
38
function caesarCipher(s, k) {
// Write your code here
const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
const pass = s.split("");
let newPass = "";
let index
for (let i = 0; i < pass.length; i++) {
const isCapital = !/[a-z]/.test(pass[i]) && /[A-Z]/.test(pass[i]);
if (isCapital) {
index = alphabet.indexOf(pass[i].toLowerCase())
} else {
index = alphabet.indexOf(pass[i])
}
if (index !== -1) {
index += k
index = index % 26
}
if (index === -1) {
newPass = newPass + pass[i]
}
else {
if (isCapital) {
newPass = newPass + alphabet[index].toUpperCase()
} else {
newPass = newPass + alphabet[index]
}
}
}
return newPass
}