Caesar Cipher

  • + 0 comments

    in JS:

    function caesarCipher(s, k) {
        const alphabets = 'abcdefghijklmnopqrstuvwxyz'
        const alLength = alphabets.length;
        let changedString = '';
        
        for (let char of s) {
            const isUpperCase = char === char.toUpperCase();
            char = char.toLowerCase();
            if (alphabets.includes(char)){
                let newIdx = (alphabets.indexOf(char) + k) % alLength;
                if (newIdx < 0) newIdx += alLength;
                let changedLetter = alphabets[newIdx];
                if (isUpperCase) {
                    changedLetter = changedLetter.toLocaleUpperCase();
                }
                changedString += changedLetter;
                
            } else {
                changedString += char;
            }
        }
        return changedString;