Caesar Cipher

  • + 0 comments

    Solution in javascript:

    function caesarCipher(s, k) {
        // Write your code here
        const alphabet = Array.from('abcdefghijklmnopqrstuvwxyz');
        const upAlphabet = Array.from('abcdefghijklmnopqrstuvwxyz'.toUpperCase());
        let l = []
        const arr = Array.from(s)
        const f = k%26
        arr.forEach(char => {
            const isLetter = alphabet.includes(char) || upAlphabet.includes(char)
            const al = alphabet.includes(char) && isLetter ? alphabet : upAlphabet; 
            if (isLetter) {
                const index = al.indexOf(char);
                if (index + k > al.length) {
                    const dex = index + f >= al.length ? (index + f) - al.length : index + f
                    l.push(al[dex])
                } else if (index + k == al.length) {
                    l.push(al[0])
                } else {
                    l.push(al[index + f])
                } 
            } else {
                l.push(char)
            }
        })
        return l.join('');
    }