Caesar Cipher

  • + 0 comments

    My answer with Typescript

    const ct = 25
    function caesarCipher(s: string, k: number): string {
        // 0. reduce k by 26 (1 circle rotation)
        k = k % (ct + 1)
    
        // 1. map character and rotation, skip special and number
        return s.split('').map(char => {
            if (!/[a-zA-Z]/.test(char)) return char;
    
            let code = char.charCodeAt(0)
            let mile = char == char.toUpperCase() ? 65 : 97
    
            if (code + k > mile + ct) return String.fromCharCode(code + k - ct - 1)
            return String.fromCharCode(code + k)
        }).join('')
    }