Skip to content

Commit fbcc54c

Browse files
committed
Add Rail Fence cipher implementation in JavaScript
1 parent 08d8c6b commit fbcc54c

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Ciphers/RailFenceCipher.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function railFenceCipher(text, rails) {
2+
if (rails <= 1) return text;
3+
4+
const fence = Array.from({ length: rails }, () => []);
5+
let rail = 0;
6+
let direction = 1;
7+
8+
for (const char of text) {
9+
fence[rail].push(char);
10+
rail += direction;
11+
12+
if (rail === 0 || rail === rails - 1) {
13+
direction *= -1;
14+
}
15+
}
16+
17+
return fence.flat().join('');
18+
}
19+
20+
module.exports = railFenceCipher;

0 commit comments

Comments
 (0)