43 encode(plaintext:
string, width: number):
string {
45 const h = Math.ceil(plaintext.length / w);
48 const grid:
string[][] = Array.from({ length: h }, () => Array(w).fill(
" "));
50 for (let r = 0; r < h; r++) {
51 for (let c = 0; c < w; c++) {
52 grid[r][c] = plaintext[index++] ??
" ";
57 const result:
string[] = [];
58 let top = 0, bottom = h - 1;
59 let left = 0, right = w - 1;
61 while (top <= bottom && left <= right) {
63 for (let c = left; c <= right; c++) {
64 result.push(grid[top][c]);
69 for (let r = top; r <= bottom; r++) {
70 result.push(grid[r][right]);
76 for (let c = right; c >= left; c--) {
77 result.push(grid[bottom][c]);
84 for (let r = bottom; r >= top; r--) {
85 result.push(grid[r][left]);
91 return result.join(
"");
99 decode(ciphertext:
string, width: number):
string {
101 const h = Math.ceil(ciphertext.length / w);
102 const grid:
string[][] = Array.from({ length: h }, () => Array(w).fill(
" "));
104 let top = 0, bottom = h - 1;
105 let left = 0, right = w - 1;
109 while (top <= bottom && left <= right) {
110 for (let c = left; c <= right; c++) {
111 grid[top][c] = ciphertext[index++] ??
" ";
115 for (let r = top; r <= bottom; r++) {
116 grid[r][right] = ciphertext[index++] ??
" ";
121 for (let c = right; c >= left; c--) {
122 grid[bottom][c] = ciphertext[index++] ??
" ";
128 for (let r = bottom; r >= top; r--) {
129 grid[r][left] = ciphertext[index++] ??
" ";
136 return grid.map(row => row.join(
"")).join(
"");