João Pedro Raskopf 9641940fd7
Add rail fence cipher (#516)
* Add rail fence cipher encoder & decoder

* Add functions to encode & decode strings using the rail fence cipher method
* Add unit tests covering empty strings, pair & odd number of characters in the input string, n=3 & n=4
* Add a README.md for the algorithm
* Update root README.md to link to the new algorithm

* Rename the CI workflow file.

Co-authored-by: Oleksii Trekhleb <trehleb@gmail.com>
2020-12-20 18:40:22 +01:00

53 lines
1.1 KiB
JavaScript

import {
addChar,
buildFence,
DIRECTIONS,
getNextDirection,
} from './railFenceCipher';
/**
* @param {object} params
* @param {number} params.railCount
* @param {number} params.currentRail
* @param {number} params.direction
* @param {Array} params.string
*
* @returns {Array}
*/
const fillEncodeFence = ({
railCount, fence, currentRail, direction, string,
}) => {
if (string.length === 0) return fence;
const [letter, ...nextString] = string;
const nextDirection = getNextDirection({ railCount, currentRail, direction });
return fillEncodeFence({
railCount,
fence: fence.map(addChar(currentRail, letter)),
currentRail: currentRail + nextDirection,
direction: nextDirection,
string: nextString,
});
};
/**
* @param {string} string
* @param {number} railCount
*
* @returns {string}
*/
export default function encodeRailFenceCipher(string, railCount) {
const fence = buildFence(railCount);
const filledFence = fillEncodeFence({
railCount,
fence,
currentRail: 0,
direction: DIRECTIONS.DOWN,
string: string.split(''),
});
return filledFence.flat().join('');
}