forked from rstropek/2018-10-ng-training
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher.ts
44 lines (37 loc) · 1.35 KB
/
cipher.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
35
36
37
38
39
40
41
42
43
44
const codeOfA = 'A'.charCodeAt(0);
const codeOfa = 'a'.charCodeAt(0);
const codeOfZ = 'Z'.charCodeAt(0);
const codeOfz = 'z'.charCodeAt(0);
const alphaBetCount = 26;
export function encrypt(plainText: string, key: number): string {
let res = '';
for (const char of plainText) {
let charCode = char.charCodeAt(0);
if ((charCode >= codeOfA && charCode <= codeOfZ) || (charCode >= codeOfa && charCode <=codeOfz)) {
const offset = charCode >= codeOfa ? codeOfa : codeOfA;
charCode = (charCode - offset + key) % alphaBetCount;
res += String.fromCharCode(charCode + offset);
} else {
res += char;
}
}
return res;
}
export function decrypt(cypherText: string, key: number): string {
let res = '';
for (const char of cypherText) {
let charCode = char.charCodeAt(0);
if ((charCode >= codeOfA && charCode <= codeOfZ) || (charCode >= codeOfa && charCode <=codeOfz)) {
const offset = charCode >= codeOfa ? codeOfa : codeOfA;
charCode = (charCode - offset - key) % alphaBetCount;
if (charCode < 0) {
res += String.fromCharCode(charCode + offset + alphaBetCount);
} else {
res += String.fromCharCode(charCode + offset);
}
} else {
res += char;
}
}
return res;
}