Skip to content

Commit 406ffb6

Browse files
committed
feat: solve vigenere-cipher
1 parent 64307b5 commit 406ffb6

File tree

1 file changed

+58
-1
lines changed

1 file changed

+58
-1
lines changed

src/vigenere-cipher.js

+58-1
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,74 @@ import { NotImplementedError } from '../extensions/index.js';
2020
*
2121
*/
2222
export default class VigenereCipheringMachine {
23-
constructor (mod) {
23+
constructor (mod = true) {
2424
this.mod = mod;
2525
}
2626
encrypt(string, key) {
2727
if (string === undefined || key === undefined) {
2828
throw new Error('Incorrect arguments!');
2929
}
30+
string = string.toUpperCase();
31+
key = key.toUpperCase();
32+
33+
let kf = Math.ceil(string.length / key.length);
34+
key = key.repeat(kf);
35+
36+
let codeA = "A".charCodeAt(0);
37+
let abcCount = 26;
38+
39+
let result = [];
40+
41+
let j = 0;
42+
for (let i = 0; i < string.length; i++) {
43+
if (string[i] === ' ' || string[i].charCodeAt(0) < 65 || string[i].charCodeAt(0) > 90) {
44+
result.push(string[i]);
45+
} else {
46+
let letterIdx = string.charCodeAt(i) - codeA;
47+
let shift = key.charCodeAt(j) - codeA;
48+
j++;
49+
50+
result.push(
51+
String.fromCharCode(codeA + (letterIdx + shift) % abcCount)
52+
);
53+
}
54+
}
55+
56+
return this.mod === false ? result.reverse().join('') : result.join('');
3057
}
3158
decrypt(string, key) {
3259
if (string === undefined || key === undefined) {
3360
throw new Error('Incorrect arguments!');
3461
}
62+
63+
string = string.toUpperCase();
64+
key = key.toUpperCase();
65+
66+
//string = this.encrypted === string ? string : string.split('').reverse().join('') === string ? string.split('').reverse().join('') : string;
67+
68+
let kf = Math.ceil(string.length / key.length);
69+
key = key.repeat(kf);
70+
71+
let codeA = "A".charCodeAt(0);
72+
let abcCount = 26;
73+
74+
let result = [];
75+
76+
let j = 0;
77+
for (let i = 0; i < string.length; i++) {
78+
if (string[i] === ' ' || string[i].charCodeAt(0) < 65 || string[i].charCodeAt(0) > 90) {
79+
result.push(string[i]);
80+
} else {
81+
let letterIdx = string.charCodeAt(i) - codeA;
82+
let shift = key.charCodeAt(j) - codeA;
83+
j++;
84+
85+
result.push(
86+
String.fromCharCode(codeA + (letterIdx - shift + abcCount) % abcCount)
87+
);
88+
}
89+
}
90+
91+
return this.mod === false ? result.reverse().join('') : result.join('');
3592
}
3693
}

0 commit comments

Comments
 (0)