-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher.js
70 lines (58 loc) · 1.42 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
export class Cipher {
encrypt(str) { return str;}
decrypt(str) { return str;}
}
export class CaesarCipher extends Cipher {
constructor(shiftNum){
super();
this.alphaArray = "abcdefghijklmnopqrstuvwxyz".split('');
this.shiftNum = shiftNum;
}
encrypt(str) {
let res = '';
const splitted = str.split('');
splitted.map((char) => {
const index = this.alphaArray.indexOf(char);
if(index == -1) {
//アルファベットでない場合
res += char;
}else{
let nextIndex = index + this.shiftNum;
//indexが26を超えたら0に戻るように余りからindexを計算
nextIndex = nextIndex % this.alphaArray.length;
const shiftedChar = this.alphaArray[nextIndex];
res += shiftedChar;
}
}, this);
return res;
}
decrypt(str) {
let res = '';
const splitted = str.split('');
splitted.map((char) => {
const index = this.alphaArray.indexOf(char);
if(index == -1) {
//アルファベットでない場合
res += char;
}else{
let nextIndex = index - this.shiftNum;
if(nextIndex < 0) {
nextIndex = this.addNumUntilPositiveOrZero(nextIndex, this.alphaArray.length);
}
const shiftedChar = this.alphaArray[nextIndex];
res += shiftedChar;
}
}, this);
return res;
}
addNumUntilPositiveOrZero(initNum, intervalNum) {
let res = initNum;
while(true) {
if(res >= 0) {
break;
}
res = initNum + intervalNum;
}
return res;
}
}