Skip to content

Instantly share code, notes, and snippets.

@holdenhinkle
Created August 30, 2019 14:21
Show Gist options
  • Save holdenhinkle/bdc66044e4b2be033be6fb79bc952bad to your computer and use it in GitHub Desktop.
Save holdenhinkle/bdc66044e4b2be033be6fb79bc952bad to your computer and use it in GitHub Desktop.
function railFenceCipher(operation, string, height = 3) {
function encrypt(string, height, fence) {
let currentRail = 0;
let moveUp = true;
let moveDown = false;
for (let i = 0; i < fence[0].length; i += 1) {
fence[currentRail].splice(i, 1, string[i]);
if ((moveUp && currentRail + 1 > height - 1) ||
(moveDown && currentRail - 1 < 0)) {
if (moveUp) currentRail -= 1;
if (moveDown) currentRail += 1;
moveUp = !moveUp;
moveDown = !moveDown;
} else if (moveUp) {
currentRail += 1;
} else if (moveDown) {
currentRail -= 1;
}
}
return fence.reduce((str, rail) => str += rail.filter(char => /\w/.test(char)).join(''), '');
}
function decrypt(string, fence) {
string = string.split('');
fence = fence.map(rail => rail.map(char => char === 'placeholder' ? string.shift() : char));
return fence.reduce((fence, rail) => fence += rail.join(' ') + '\n', '');
}
function addPlaceholders(fence, numberOfRails) {
let cycle = numberOfRails * 2 - 2;
fence.forEach((rail, index) => {
const processRail = (rail, railIndex) => {
while (railIndex < rail.length ) {
rail.splice(railIndex, 1, 'placeholder');
railIndex += cycle;
}
}
let railIndex = index;
let railNumber = index + 1;
processRail(rail, railIndex);
if (railNumber > 1 && railNumber < fence.length) {
railIndex = cycle - railNumber + 1;
processRail(rail, railIndex);
}
});
return fence;
}
if (operation === 'encrypt' && height === 1) {
return 'Height must be 2 or more.';
}
string = string.replace(/\W/g, '');
fence = [...Array(height)].map((_, i) => i)
.map(rail => [...Array(string.length)].map((_, i) => i))
.map(rail => rail.map(element => '.'));
if (operation === 'encrypt') {
return encrypt(string, height, fence);
} else if (operation === 'decrypt') {
return decrypt(string, addPlaceholders(fence, height));
}
}
cipherText = 'WECRLTEERDSOEEFEAOCAIVDEN';
console.log(railFenceCipher('decrypt', cipherText, 3));
cipherText = '[IA_EZS]_ELYLK_UZERLIPL';
console.log(railFenceCipher('decrypt', cipherText, 3));
cipherText = 'INLLUCOOAHOVLSHEC';
console.log(railFenceCipher('decrypt', cipherText, 5));
message = 'WE ARE DISCOVERED FLEE AT ONCE';
console.log(railFenceCipher('encrypt', message, 3));
message = 'I LOVE LAUNCH SCHOOL!';
console.log(railFenceCipher('encrypt', message, 5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment