Home > OS >  Caesar Cipher - FCC / Javascript - I can't figure out if why the result is not right
Caesar Cipher - FCC / Javascript - I can't figure out if why the result is not right

Time:09-11

I have tried to solve the Caesar Cipher project of FCC with a few inspirations from the web but I can't figure out why my following code isn't working.

I think it's a problem between charCodeAt() and the result integration in the array?!

I would like to use this version rather than creating an object as it seems way more efficient and a good reminder for later purposes.

function rot13(str) {

    str = str.toUpperCase();
    let arr = str.split('');

    for (let i = 0; i > arr.length; i  ) {
        let charLetter = arr[i];
        if (charLetter.match(/[A-Z]/g)){
            charValue = arr[i].charCodeAt();
                if (charValue <= 'N'.charCodeAt()) {
                    charChange = (charValue   13);
                }
                else {
                    charChange = (charValue - 13);
                }
            }
            let result = result.push(charChange);
        }
        return result.join('')
}

rot13("SERR PBQR PNZC");

CodePudding user response:

When working on a rot13 exercise, fiddling with char codes is cumbersome and error prone. Consider this approach instead:

abc = "abcdefghijklmnopqrstuvwxyz"
key = "nopqrstuvwxyzabcdefghijklm"

for (char of text) {
    index = abc.indexOf(char)
    result  = index >= 0 ? key[index] : char 
}

Later on, you can extend this to encode a generic caesar by generating key dynamically from the alphabet and a shift value.

  • Related