Caesar alghorithm

by aninaslyan

JavaScript

function chipher(str, num) {
	let alphabet = "abcdefghijklmnopqrstuvwxyz";
  let coded = "";
  
  for (let i=0; i<str.length; i++) {
  	let index = alphabet.indexOf(str[i]);
    let newIndex = index + num;
    
    if(newIndex > 25) {
    	newIndex -= 26;
    }
    if(str[i] === str[i].toUpperCase()) {
    	coded += alphabet[newIndex].toUpperCase();
    } else {
    	coded += alphabet[newIndex];
    }
    
    if(str[i] === " ") {
    	coded = coded + alphabet[newIndex] + " ";
    }
  }
   return coded;
}

text = prompt("Input text");
console.log(chipher(text, 3));




function rot13(str) {
      // Split str into a character array
      return str.split('')
      // Iterate over each character in the array
        .map.call(str, function(char) {
          // Convert char to a character code
          let x = char.charCodeAt(0);
          // Checks if character lies between A-Z
          if (x < 65 || x > 90) {
            return String.fromCharCode(x);  // Return un-converted character
          }
          //N = ASCII 78, if the character code is less than 78, shift forward 13 places
          else if (x < 78) {
            return String.fromCharCode(x + 13);
          }
          // Otherwise shift the character 13 places backward
          return String.fromCharCode(x - 13);
        }).join('');  // Rejoin the array into a string
    }

// Change the inputs below to test
rot13("SERR PBQR PNZC");