Search code examples
javascriptloopsfor-loopcaesar-cipher

Caesar Cipher (How do I convert for into .map)


It's a Caesar cipher program, I have written this code by myself and want to convert this for loop into .map JavaScript built-in function, I have tried so many times but can't figure out.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

There are many questions on .map on this website but that doesn't work for me.

function rot13(str) {
   var chArray = [];
   str = str.split("");
   
   for(var i in str){
    var char = str[i].charCodeAt(0);
     if(/[A-M]/g.test(str[i])){
       chArray.push(char + 13);
     }
     else if(/[N-Z]/g.test(str[i])){
       chArray.push(char - 13);
     }
     else chArray.push(char);
   }
   str = String.fromCharCode.apply(String,chArray);
  return str;
}

rot13("SERR PBQR PNZC");


Solution

  • If you want to do this very compactly, you can do the following:

    const A = 'A'.charCodeAt(0)
    const M = 'M'.charCodeAt(0)
    const N = 'N'.charCodeAt(0)
    const Z = 'Z'.charCodeAt(0)
    function rot13(str) {
       var chArray = [];
       return String.fromCharCode(...(
         str.split('')
           .map(c => c.charCodeAt(0))
           .map(c =>
             (A <= c && c <= M) ? c + 13 :
             (N <= c && c <= Z) ? c - 13 :
             c
           )
       ))
    }
    
    console.log(rot13("SERR PBQR PNZC"))