Last active
September 21, 2021 17:27
-
-
Save TMUniversal/55c2aeaa423185988ac31a53bb5c7820 to your computer and use it in GitHub Desktop.
(De-)cipher caesar encryption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const alphabet = "abcdefghijklmnopqrstuvwxyz" | |
function caesar(input: string, offset: number): string { | |
const result: string[] = [] | |
for (const character of input) { | |
// Calculate caesar offset | |
let offsetIndex: number = alphabet.indexOf(character) + offset | |
// Move indices that are out of bounds back in | |
if (offsetIndex < 0) offsetIndex = alphabet.length + offsetIndex | |
if (offsetIndex > alphabet.length) | |
offsetIndex = offsetIndex - alphabet.length | |
// Keep spaces, convert all control characters (i.e. \n or \t) to spaces | |
let char: string = character | |
if (/\s/iu.test(character)) char = " " | |
else char = alphabet.charAt(offsetIndex) | |
result.push(char) | |
} | |
return result.join("") | |
} | |
const input: string = | |
"cebtenzzvrerafvrvzzrefbnyfjnrerqreglcqreqrapbqrcsyr" + | |
"\n" + | |
"trazhffrvatrjnygorervgrecflpubcnguqrejrvffjbfvrjbuara" | |
console.log("Input:", input) | |
for (let i = -1; i > -alphabet.length; i--) { | |
console.log(`Offset: ${i}\tmsg: ${caesar(input, i)}`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment