44 encode(plainText:
string, rails: number = 3):
string {
49 const rows:
string[][] = Array.from({ length: rails }, () => []);
53 for (
const character of plainText) {
54 rows[currentRow].push(character);
56 currentRow += direction;
59 if (currentRow === rails - 1 || currentRow === 0) {
65 const cipherText = rows.map(row => row.join(
"")).join(
"");
78 decode(cipherText:
string, rails: number = 3):
string {
83 const textLength = cipherText.length;
84 const railPattern: number[] = [];
90 for (let i = 0; i < textLength; i++) {
91 railPattern.push(currentRow);
93 currentRow += direction;
95 if (currentRow === rails - 1 || currentRow === 0) {
101 const railCharacterCounts = Array(rails).fill(0);
102 for (
const rowIndex of railPattern) {
103 railCharacterCounts[rowIndex]++;
107 const railsContent:
string[][] = Array.from({ length: rails }, () => []);
108 let currentPosition = 0;
110 for (let rowIndex = 0; rowIndex < rails; rowIndex++) {
111 const rowLength = railCharacterCounts[rowIndex];
112 const rowCharacters = cipherText
113 .slice(currentPosition, currentPosition + rowLength)
116 railsContent[rowIndex] = rowCharacters;
117 currentPosition += rowLength;
121 const rowIndices = Array(rails).fill(0);
124 for (
const rowIndex of railPattern) {
125 plainText += railsContent[rowIndex][rowIndices[rowIndex]];
126 rowIndices[rowIndex]++;