시저 암호

const UPPERCASE = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
];
const LOWERCASE = [
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
];

const isUpperCase = (char) => char == char.toUpperCase();

const mapHelper = (char, n) => {
  if (char == " ") {
    return " ";
  }
  if (isUpperCase(char)) {
    const index = UPPERCASE.indexOf(char);
    const dividedIndex = (index + n) % UPPERCASE.length;
    return UPPERCASE[dividedIndex];
  }
  const index = LOWERCASE.indexOf(char);
  const dividedIndex = (index + n) % LOWERCASE.length;
  return LOWERCASE[dividedIndex];
};

const solution = (s, n) => {
  return s
    .split("")
    .map((char) => mapHelper(char, n))
    .join("");
};
  • 처음에는 아스키 코드를 이용해서 풀려고 했으나 생각보다 간단한 것 같지 않아서 노가다를 선택해버렸다

0개의 댓글