mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2024-11-09 22:08:58 +01:00
feat(solution): add typescript-caesar-cipher
This commit is contained in:
parent
229dcf03c3
commit
253421fee9
@ -0,0 +1,5 @@
|
|||||||
|
# typescript-caesar-cipher - caesar-cipher
|
||||||
|
|
||||||
|
Programming language : TypeScript
|
||||||
|
|
||||||
|
Created by [@Divlo](https://github.com/Divlo) on 21 October 2020.
|
@ -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
|
Loading…
Reference in New Issue
Block a user