| 8 | 8 | * @param {string} input |
| 9 | 9 | */ |
| 10 | 10 | constructor(input) { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 11 | // Edge Case: empty input string |
| 12 | if (!input) { |
| 13 | this.normalized = ''; |
| 14 | return; |
| 15 | } |
| 16 | |
| 17 | // Normalize the input: remove spaces and punctuation, convert to lowercase |
| 18 | this.normalized = input.toLowerCase().replace(/[^a-z0-9]/g, ''); |
| 12 | 19 | } |
| 13 | 20 | |
| 14 | 21 | /** |
| 15 | 22 | * @returns {string} |
| 16 | 23 | */ |
| 17 | 24 | get ciphertext() { |
| 18 | | throw new Error('Remove this line and implement the function'); |
| 25 | // Edge Case: empty normalized string |
| 26 | if (!this.normalized) { |
| 27 | return ''; |
| 28 | } |
| 29 | |
| 30 | const len = this.normalized.length; |
| 31 | |
| 32 | // Edge Case: single character input |
| 33 | if (len === 1) { |
| 34 | return this.normalized; |
| 35 | } |
| 36 | |
| 37 | // Find the dimensions of the rectangle |
| 38 | // Calculate the smallest c such that r * c >= len, c >= r, and c - r <= 1 |
| 39 | let c = Math.ceil(Math.sqrt(len)); |
| 40 | let r = Math.ceil(len / c); |
| 41 | |
| 42 | // Ensure c >= r and c - r <= 1 |
| 43 | while (c < r || c - r > 1) { |
| 44 | if (c < r) { |
| 45 | c = r; |
| 46 | } else { |
| 47 | c++; |
| 48 | r = Math.ceil(len / c); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Create the rectangle by filling rows |
| 53 | const rectangle = []; |
| 54 | for (let i = 0; i < r; i++) { |
| 55 | const start = i * c; |
| 56 | let row = this.normalized.slice(start, start + c); |
| 57 | // Pad the row with spaces if needed |
| 58 | while (row.length < c) { |
| 59 | row += ' '; |
| 60 | } |
| 61 | rectangle.push(row); |
| 62 | } |
| 63 | |
| 64 | // Read down the columns to create the encoded message |
| 65 | let encoded = ''; |
| 66 | for (let col = 0; col < c; col++) { |
| 67 | for (let row = 0; row < r; row++) { |
| 68 | encoded += rectangle[row][col]; |
| 69 | } |
| 70 | // Add space between chunks except for the last chunk |
| 71 | if (col < c - 1) { |
| 72 | encoded += ' '; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | return encoded; |
| 19 | 77 | } |
| 78 | |
| 79 | // Handled Edge Cases: empty input string, single character input, perfect square length text |
| 20 | 80 | } |