-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
34 lines (26 loc) · 807 Bytes
/
index.ts
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
function caesarCipher(str: string, num: number): string {
const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
const lowerStr = str.toLowerCase();
const position = num % alphabet.length;
let newString = "";
for (let i = 0; i < lowerStr.length; i++) {
const currentLetter = lowerStr[i];
if (currentLetter === " ") {
newString += currentLetter;
} else {
let newIndex = alphabet.indexOf(currentLetter) + position;
if (newIndex > 25) {
newIndex -= alphabet.length;
}
if (newIndex < 0) {
newIndex = alphabet.length + newIndex;
}
newString +=
str[i] === str[i].toUpperCase()
? alphabet[newIndex].toUpperCase()
: alphabet[newIndex];
}
}
return newString;
}
export default caesarCipher;