/
script.js
57 lines (52 loc) · 2 KB
/
script.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class CaesarCipher {
constructor(newRotation) {
this.rotation = newRotation;
}
lowerCaseAlpha = 'abcdefghijklmnopqrstuvwxyz';
upperCaseAlpha = this.lowerCaseAlpha.toUpperCase();
alphaLength = 26;
encrypt(str) {
let cipherText = '';
for (let i = 0; i < str.length; i++) {
if (this.lowerCaseAlpha.includes(str[i])) {
let index = this.getIndex(true, this.lowerCaseAlpha, str[i]);
cipherText += this.lowerCaseAlpha[index];
} else if (this.upperCaseAlpha.includes(str[i])) {
let index = this.getIndex(true, this.upperCaseAlpha, str[i]);
cipherText += this.upperCaseAlpha[index];
} else {
cipherText += str[i];
}
}
return cipherText;
}
decrypt(str) {
let plainText = '';
for (let i = 0; i < str.length; i++) {
if (this.lowerCaseAlpha.includes(str[i])) {
let index = this.getIndex(false, this.lowerCaseAlpha, str[i]);
plainText += this.lowerCaseAlpha[index];
} else if (this.upperCaseAlpha.includes([str[i]])) {
let index = this.getIndex(false, this.upperCaseAlpha, str[i]);
plainText += this.upperCaseAlpha[index];
} else {
plainText += str[i];
}
}
return plainText;
}
getIndex(isEncrypt, casing, char) {
/*
Modulo calculation taken from: https://stackoverflow.com/a/13163436,
to prevent negative results
*/
if (isEncrypt) {
let remain = (casing.indexOf(char) + this.rotation) % this.alphaLength;
return Math.floor(remain >= 0 ? remain : remain + this.alphaLength);
} else if (!isEncrypt) {
let remain = (casing.indexOf(char) - this.rotation) % this.alphaLength;
return Math.floor(remain >= 0 ? remain : remain + this.alphaLength);
}
}
}
export {CaesarCipher};