@@ -20,17 +20,74 @@ import { NotImplementedError } from '../extensions/index.js';
20
20
*
21
21
*/
22
22
export default class VigenereCipheringMachine {
23
- constructor ( mod ) {
23
+ constructor ( mod = true ) {
24
24
this . mod = mod ;
25
25
}
26
26
encrypt ( string , key ) {
27
27
if ( string === undefined || key === undefined ) {
28
28
throw new Error ( 'Incorrect arguments!' ) ;
29
29
}
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 ( '' ) ;
30
57
}
31
58
decrypt ( string , key ) {
32
59
if ( string === undefined || key === undefined ) {
33
60
throw new Error ( 'Incorrect arguments!' ) ;
34
61
}
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 ( '' ) ;
35
92
}
36
93
}
0 commit comments