Caesars Cipher

ManasaVeena Patel
3 min readJul 28, 2021

JavaScript Algorithms and Data Structures Projects — freeCodeCamp

Cipher, Caesar Cipher

Problem Description :

One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.

A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus A ↔ N, B ↔ O and so on.

Write a function which takes a ROT13 encoded string as input and returns a decoded string.

All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.

Solution Steps:

  • We will be given a string of letters and other characters which is already encoded in ROT13 cipher encryption technique. We need to decode only letters of the string and pass the other characters as it is.
ROT13 Cipher Encryption Technique
  • As strings are immutable objects, we can convert the given string into an array using split() method to deal with each single character in it and pass it’s decoded/same form based on the condition.
  • Two methods we use here are : charCodeAt(index) and String.fromCharCode(code)
charCodeAt(index) method
String.fromCharCode(code) method
  • In ROT13 cipher encryption/decryption technique: for A-M letters, we can add 13 to it’s ASCII value and for N-Z letters, we can subtract 13 from it’s ASCII value to get the decoded letter of it. By iterating over the given string in array form, we can replace each element with it’s decoded character as per the logic below.
  • Now that, all characters which have ASCII value not in range of 65–90 will be passed to the strArray as it is. The characters which have ASCII value in range of 65–77 will be passed with decoded character of +13 ASCII code and the characters which have ASCII value in range of 78–90 will be passed with decoded character of -13 ASCII code.
  • We have strArray ready with decoded characters, just convert it into a string again and return it.
  • Here is the code:
function rot13(str) {
let strArray = str.split('');

for(let i = 0; i<strArray.length; i++){
let code = strArray[i].charCodeAt(0);
strArray[i] = code<65 || code>90 ? strArray[i]
: code>=78 && code<=90 ?
String.fromCharCode(code-13)
: String.fromCharCode(code+13);
}

return strArray.join('');
}

rot13("E");

Thank You !

I would be happy to hear your suggestions/improvements.

--

--

ManasaVeena Patel

Eat, Code, Read, Write, Sleep, Laugh - That's me in simple words!