0

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");
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Reggroy
  • 53
  • 5
  • You should define `result` before you use `result.push`. As you access it in the whole function you can put `let result = []` to the top of it – A_A Sep 11 '22 at 11:52
  • 1
    Also, you should use [String.fromCharCode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode). And the loop condition seems wrong – A_A Sep 11 '22 at 11:53
  • Thanks, definitely full of mistakes. I will get back to it and thanks. – Reggroy Sep 11 '22 at 12:03

1 Answers1

0

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.

gog
  • 10,367
  • 2
  • 24
  • 38
  • Thanks a lot! It seems so simple right now, I tried something bigger than I was able to handle. – Reggroy Sep 11 '22 at 12:28