Search code examples
javascriptencryptioncaesar-cipher

Solve Caesers Cipher Using a switch code in Javascript


You may be familiar with caeser cipher(see this wiki on caesers cipher AKA ROT13)

I have been looking at solutions for the cipher but I do not see anyone using a switch statement. Given the challenge (see below), can this problem be simply solved by using a switch statement? I have put my code below but it does not work.

function cciph(str) { 
  var code = "";

  switch {switch (str) {
    case 'A':
      code = "N";
      break;
    case 'B:
      code = 'O';
      break;
      //.....
    case 'M':  code = 'Z';
  }
  return str; 
}

cciph("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");

Solution

  • I don't know about a switch, but this will give you all 26 possible mutations of the string, theoretically including the decoded string.

    var alphabet = ["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"];
    
    
    function cciph(cipherText) {
      for(i = 0; i < 26; i++) {
        var decodedText = cipherText.split("").map(function(c) {
          var charIndex = alphabet.indexOf(c.toLowerCase());
          if (charIndex == -1) {
            return c;
          }
          var modifiedIndex = charIndex + i;
          var correctedIndex = modifiedIndex % 26;
          return alphabet[correctedIndex];
        });
        console.log(decodedText.join(""));
      }
    }
    
    cciph("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");