-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto-square.js
40 lines (30 loc) · 925 Bytes
/
crypto-square.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
const isAlphaNumeric = c =>
(c >= "0" && c <= "9") || (c >= "A" && c <= "Z") || (c >= "a" && c <= "z");
const normalizePlaintext = plaintext =>
[...plaintext.toLowerCase()].filter(isAlphaNumeric).join("");
export class Crypto {
constructor(plaintext) {
this._plaintext = plaintext;
}
normalizePlaintext() {
return normalizePlaintext(this._plaintext);
}
size() {
return Math.ceil(Math.sqrt(this.normalizePlaintext().length));
}
plaintextSegments() {
const numColumns = this.size(),
text = this.normalizePlaintext();
let segments = [];
for (let i = 0; i < text.length; i += numColumns) {
segments.push(text.slice(i, i + numColumns));
}
return segments;
}
ciphertext() {
const messageSquare = this.plaintextSegments();
return Array.from(messageSquare, (_, col) =>
messageSquare.map(segment => segment[col]).join("")
).join("");
}
}