My Solution for Caesar's Cipher

Under a spoiler cut. I used an object lookup, which apparently isn’t the most common or most optimal approach, but I got it to work. There are some possible methods for solving this I need to learn more about, like charCodeAt().

function rot13(str) {
//Create object to use inside the function.
const caesarLookup = {
  "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",
};
  // Split string into an array
  const codedArray = str.split("");
  const decodedArray = codedArray.map(char =>
  caesarLookup[char] || char);
  // Use the map function to convert characters into their Caesar cypher equivalents. The or statement specifies that characters not found in the lookup object remain the same.
  const decodedString = decodedArray.join("");
  return decodedString;
  //Convert decoded array into a string and return it.
}

Object lookup may not be the most common, but it is definitely one of the fastest solutions, since such a search has constant complexity. As an optimization, you could generate such a table programmatically outside the function.

Another approach, as you mentioned, might be to use the charCodeAt() method, since the Latin letter codes go in the same sequence as in the alphabet, and knowing the letter code, you can determine the “shifted” code.

function rot13(str) {
  const A = 'A'.charCodeAt(0)
  const R = 26 // num En letters
  const S = 13 // shift
  return str.replace(/[A-Z]/g, 
    (c) => String.fromCharCode(((c.charCodeAt(0) - A + S) % R) + A));
}

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