Need feedback on my Javascript for Caesars Cipher

Hi all, I have just finished “Caesars Cipher” on Javascript Algorithm curriculum. I hope you can give me feedback on my work. It took me 2 hours something improving on my program.

function rot13(str) {

  const MIN = 65, 
        MAX = 90, 
        MID = 77,
        ROT_13 = 13;
  const newName = str.split(" ");
  let charArray = [];

  function numToAscii(val) {  //function to return an ASCII value of a decimal number
    return String.fromCharCode(val);
  }

  for (let i in newName) {
      charArray[i] = newName[i].split("").map(  //do the split, map and join
        function (charValue) {
          let numValue = charValue.charCodeAt(0);  //get character decimal value 
          if (numValue < MIN || numValue > MAX) {
            return numToAscii(numValue);  //do nothing, just return the decimal value if char is not a letter
          } else if (numValue > MID) {
            return numToAscii((MIN - 1) + (ROT_13 - (MAX - numValue)));  //in case decimal value is more than MID return calculated result
          } else {
            return numToAscii(numValue + 13); //add 13 to decimal value
          }
        }
      ).join("");
  }

  return charArray.join(" ");
}

rot13("SERR PBQR PNZC");

Cool.

I blurred your answer by surrounding it with [spoiler[ tags, since it is a working answer.

But yeah, it looks good. I might suggest that you could simplify the logic a bit. Once you’ve established that it is an alphabetic character, I think the math could be a little simpler:

          if (numValue < MIN || numValue > MAX) {
            return numToAscii(numValue);  //do nothing, just return the decimal value if char is not a letter
          } else {
            const rotatedValue = numValue + 13;
            return numToAscii(rotatedValue > MAX ? rotatedValue - 26 : rotatedValue)
          } 

If I’m being picky, I might argue that variable names like “MIN” and “MAX” are vague. I might have done something like A_CHAR_VALUE and Z_CHAR_VALUE to make it clearer in the code. But others may disagree.

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