caesar encryption code example

Example 1: caesar cipher

function caesarCipher(str, shift) {
  const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split("");
  let res = "";

  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    const idx = alphabetArr.indexOf(char);

    // if it is not a letter, don`t shift it
    if (idx === -1) {
      res += char;
      continue;
    }

    // only 26 letters in alphabet, if > 26 it wraps around
    const encodedIdx = (idx + shift) % 26;
    res += alphabetArr[encodedIdx];
  }
  return res;
}

Example 2: Caesars Cipher

const rot13 = str => {
  let decodedCipher = ''
    // The number 65 represents A which also is the begining of our alphabets. 
    // The number 90 represents Z which also is the end of our alphabets.
    // Space and any other non-alpha character is less than 65(A) and greater than 90(Z).

    // Split and loop over every character
  str.split('').forEach(character => {
    	// Get the integer or unicode for ever character which returns a number and store it in letterChar
    const letterChar = character.charCodeAt()
    
      // Check if number(letterChar) is less than 65(A) or greater than 90(Z)
      // If true, return the number(letterChar) which means, it could be a non-alpha character
      // If false, return the number(letterChar) + 13, which means it has shifted 13 places.
    let unicode = letterChar < 65 || letterChar > 90 ? letterChar : letterChar + 13

      // unicode minus 1 is greater or equal to 90(Z)
      // Set unicode to equal unicode minus 1, 
      // we minus 1 cause unicode will give us the right operand instead of the left operand
      // eg N + 13 will give us B instead of A, so,
      // We substract the now(unicode-1) unicode from 90 to get the number left, then we add it to 65(A),
      // Cause we start from begining after we've met the end
    if((unicode - 1) >= 90) unicode = (((unicode - 1) - 90) + 65)

    	// Convert and add every character to cipher
    decodedCipher += String.fromCharCode(unicode)
  })

  return decodedCipher;
}

rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.");

// With love @kouqhar