Skip to content

Instantly share code, notes, and snippets.

@Git-I985
Created November 20, 2023 11:21
Show Gist options
  • Save Git-I985/7f18c3e537031575d6bef8bd3a8030cd to your computer and use it in GitHub Desktop.
Save Git-I985/7f18c3e537031575d6bef8bd3a8030cd to your computer and use it in GitHub Desktop.
Rail fence cipher
function getSteps(currentRail, numberRails) {
let step1 = (currentRail === numberRails) || (currentRail === 1) ? ((numberRails - 1) * 2) : ((numberRails - currentRail) * 2);
let step2 = (currentRail === numberRails) || (currentRail === 1) ? (step1) : ((currentRail - 1) * 2);
return [step1, step2]
}
function encodeRailFenceCipher(string, numberRails) {
let res = ''
for (let currentRail = 1; currentRail <= numberRails; currentRail++) {
const [step1, step2] = getSteps(currentRail, numberRails)
let step;
for (let letter = currentRail - 1; letter < string.length; letter += step) {
res += string[letter]
step = step === step1 ? step2 : step1
}
}
return res
}
function decodeRailFenceCipher(string, numberRails) {
let res = []
const iterator = string[Symbol.iterator]()
for (let currentRail = 1; currentRail <= numberRails; currentRail++) {
const [step1, step2] = getSteps(currentRail, numberRails)
let step;
for (let letterIndex = currentRail - 1; letterIndex < string.length; letterIndex += step) {
res[letterIndex] = iterator.next().value
step = step === step1 ? step2 : step1
}
}
return res.join('')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment