javascriptunit-testingencryptioncaesar-ciphercodesandbox

Caesar Cipher Shift Letters Issue


I was trying to program a caesar cipher using the technique of converting letter by letter with an ASCII Converter then shift the numbers and convert them again in text but it works only if the letters don't go over the z with the shift.

const checkPunctuation = (text) => {
  return /[.,#!$%^&*;:{}=\-_`~()]/g.test(text);
};

const ASCIIConverter = (text) => {
  return text.split("").map((char) => {
    return checkPunctuation(char) ? char : char.charCodeAt();
  });
};

const caesarCipher = (text, shift) => {
  return ASCIIConverter(text)
    .map((code) => (code + shift) % 26)
    .map((charCode) => String.fromCharCode(charCode))
    .join("");
};
console.log(caesarCipher("pizza!", 2));

Expected: wpggh!

Received: (Box Characters with a mark)


Solution

  • Some issues:

    Here is the proposed correction:

    const convertRange = (text, regex, a, shift) =>
      text.replace(regex, letter => 
        String.fromCharCode(
          (letter.charCodeAt() - a.charCodeAt() + shift) % 26 + a.charCodeAt()
        )
      );
    
    const caesarCipher = (text, shift) => {
      text = convertRange(text, /[A-Z]/g, 'A', shift); // Cypher uppercase
      return convertRange(text, /[a-z]/g, 'a', shift); // Cypher lowercase
    };
    
    console.log(caesarCipher("pizza!", 7));