Caesar Cipher

  • + 0 comments

    I solved it slightly differently using Typescript. I created a dictionary that will have the original letter as the key and then the rotated letter as the value. I then iterate over the string and map that char to the dictionary and check for special chars or uppercase (regex) into a new string

    ` function caesarCipher(s: string, k: number): string { // Write your code here const alph = 'abcdefghijklmnopqrstuvwxyz' const dic: Dictionary = {} for (let i = 0; i < alph.length; i++) { const rotated = (i + k) % 26 dic[alph[i]] = alph[rotated] }

    let decypher = ''
    let pattern = /[A-Z]/g;
    for (let i = 0; i< s.length; i++) {
        // check for uppercase
        if (s[i].match(pattern)) {
            const lower = dic[s[i].toLowerCase()]
            decypher += lower.toUpperCase()
        } else {
                // if in dictionary add the value else add the original special char
            decypher += dic[s[i]] ?? s[i]
        }
    
    }
    return decypher
    

    }