• + 0 comments

    My answer in Typescript

    const letter = 26;
    const encrypt_char = (char: string, k: number): string => {
        k = k % letter
    
        // ASCII codes
        let ct_min, ct_max = 0
        if (/([a-z])/.test(char)) ct_max = (ct_min = 97) + letter - 1;
        if (/([A-Z])/.test(char)) ct_max = (ct_min = 65) + letter - 1;
    
        // Only encrypt letter (mean a-z or A-Z)
        if (!ct_min || !ct_max) return char;
    
        let code = char.charCodeAt(0)
        let code_encrypted = code + k
    
        if (code_encrypted > ct_max) code_encrypted -= letter
        return String.fromCharCode(code_encrypted)
    }
    function caesarCipher(s: string, k: number): string {
        // doin encrypt every character in string
        return s.split('').map(c => encrypt_char(c, k)).join('')
    }