Caesars Cipher - very close to completing

Hi,

My code is working in ciphering this challenge.

However I am having difficulty translating the ciphered code back into letters.

I am using String.fromCharCode and passing in a variable.

Frustratingly if I console.log the values of this variable and copy and paste them into String.fromCharCode it works!

Your code so far


function rot13(str) {

let answerArray = [];


for(let i = 0; i <str.length; i++){
    answerArray.push(str.charCodeAt(i))
}

//use if statement to set rule for capital letters only, seperate statement if +13 will move out of alphabet range.

console.log('answerArray', answerArray)

let transformedArray = answerArray.map(x => {
        if (x >= 65 && x <= 77){
            return x + 13;
        } else if(x >= 78 && x <= 90){
            return x + 13 - 26;
        } else {
            return x;
        }
    }
);


console.log('transformedArray', transformedArray);

let transformedStr = transformedArray.join(',');


console.log('transformedStr', transformedStr);

console.log(String.fromCharCode(transformedStr))

return String.fromCharCode(transformedStr)




// get character code for each letter
//map it to +13. If over 26 set to zero and start again
//pass non-letters through





}

// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher

fromCharCode() accepts numbers as parameters separated by a comma. like this:

String.fromCharCode(65, 67, 68) ;

or accepts a bunch of strings like this:

String.fromCharCode('65', '67', '68');

which get converted to numbers by JS behind the scenes thanks to type coercion.

What you are trying to do is pass ONE big string as an argument, which JS can’t make sense of.

String.fromCharCode('65, 67, 68');

So, a better idea when working with your array would be to call the method individually for each number that you are trying to convert

1 Like

You are close. Instead of using join with the , as the delimiter after the transformedArray is created, I suggest using fromCharCode inside the map callback so you end up with an array of characters (instead of codes) which could be “joined” with a blank string as the delimiter. right before returning in the main function.

1 Like