# Caesars Cipher challenge - Is my solution to basic?

I just did the Caesars Cipher challenge from the Javascript Curriculum . I felt my approach was kind of too basic. Then I looked at some forum posts to see other people’s approaches. Some of them looked a little fancier, using some math and getting the character code. But I still considered my approach to be better, for simplicity and readability reasons.

I wanted to know your opinions on my code. Am I missing something? Is my code inefficient or slow for some reason?

``````function rot13(str) {

//First, create an object where the keys are the letters in the alphabet and the values are the equivalent letters using the ROT13 cipher.
const table = {
'A': 'N',
'B': 'O',
'C': 'P',
'D': 'Q',
'E': 'R',
'F': 'S',
'G': 'T',
'H': 'U',
'I': 'V',
'J': 'W',
'K': 'X',
'L': 'Y',
'M': 'Z',
'N': 'A',
'O': 'B',
'P': 'C',
'Q': 'D',
'R': 'E',
'S': 'F',
'T': 'G',
'U': 'H',
'V': 'I',
'W': 'J',
'X': 'K',
'Y': 'L',
'Z': 'M'
}

//Then, get the string and split it into an array. Also, create a new empty array to receive the results
const arr = str.split('')
const result = []

//Then, iterate through the characters in the array. If it is a letter, it finds the key in the object which corresponds to the letter and pushes the value (which is the ROT13 cipher letter) into the 'result' array. If it is not a letter (say, a whitespace or number), it pushes the same character into the 'result' array
for (let letter of arr){
if (table.hasOwnProperty(letter)){
result.push(table[letter])
} else {result.push(letter)}
}

//Lastly, it joins the characters in the result array and returns the expected output
return result.join('');
}

console.log(rot13("SERR PBQR PNZC"));
``````

You approach is fine for the requirements of this challenge. But what if you needed the function to be able to handle any amount of shift? Or what if you wanted to allow a wider range of characters? Would you want to write a new function for each possibility or would you want to write just one function that could handle anything you threw at it?

The more flexible your function is the more situations it can be used in, and that is usually considered a good thing.

Exactly what I was going to say. Also, this challenge is a useful exercise in dealing with charCodes and basic algorithms for manipulating such values.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.