From 253421fee90fea1f6bb06167f5ec4fbba787a187 Mon Sep 17 00:00:00 2001 From: divlo Date: Wed, 21 Oct 2020 11:30:48 +0200 Subject: [PATCH] feat(solution): add typescript-caesar-cipher --- .../typescript-caesar-cipher/README.md | 5 +++ .../typescript-caesar-cipher/solution.ts | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 challenges/caesar-cipher/solutions/typescript-caesar-cipher/README.md create mode 100644 challenges/caesar-cipher/solutions/typescript-caesar-cipher/solution.ts diff --git a/challenges/caesar-cipher/solutions/typescript-caesar-cipher/README.md b/challenges/caesar-cipher/solutions/typescript-caesar-cipher/README.md new file mode 100644 index 0000000..7698fae --- /dev/null +++ b/challenges/caesar-cipher/solutions/typescript-caesar-cipher/README.md @@ -0,0 +1,5 @@ +# typescript-caesar-cipher - caesar-cipher + +Programming language : TypeScript + +Created by [@Divlo](https://github.com/Divlo) on 21 October 2020. diff --git a/challenges/caesar-cipher/solutions/typescript-caesar-cipher/solution.ts b/challenges/caesar-cipher/solutions/typescript-caesar-cipher/solution.ts new file mode 100644 index 0000000..a8a0a41 --- /dev/null +++ b/challenges/caesar-cipher/solutions/typescript-caesar-cipher/solution.ts @@ -0,0 +1,42 @@ +const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('') + +interface ShiftedLetter { + origin: string + shifted: string +} + +function shiftAlphabet (shift: number): ShiftedLetter[] { + const result: ShiftedLetter[] = [] + for (let index = 0; index < alphabet.length; index++) { + const letter = alphabet[index] + let shiftedIndex = index + shift + if (shiftedIndex > alphabet.length - 1) { + shiftedIndex = Math.abs(alphabet.length - shiftedIndex) + } + result.push({ + origin: letter, + shifted: alphabet[shiftedIndex] + }) + } + return result +} + +function solution (str: string, shift: number): string { + const shiftedAlphabet = shiftAlphabet(shift) + let result = '' + for (const letter of str) { + if (letter === ' ') { + result += ' ' + } else { + for (const { origin, shifted } of shiftedAlphabet) { + if (letter === shifted) { + result += origin + break + } + } + } + } + return result +} + +export default solution