Encrypting a string using Caesar Cipher in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Caesar Cipher Algorithm

The Caesar Cipher algorithm is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet.

For example

With a left shift of 3, D would be replaced by A, E would become B, and so on. We are required to write a JavaScript function that takes in a string to be encrypted as the first argument and a shift amount as the second argument.

The shift amount can be a positive or negative integer (a positive shift signifies a shift to right whereas negative to left).

Example

Following is the code −

const str = 'thisIsAString';
const getMap = (legend, shift) => {
   return legend.reduce((charsMap, currentChar, charIndex) => {
      const copy = { ...charsMap };
      let ind = (charIndex + shift) % legend.length;
      if (ind < 0) {
         ind += legend.length;
      };
      copy[currentChar] = legend[ind];
      return copy;
   }, {});
};
const encrypt = (str, shift = 0) => {
   const legend = 'abcdefghijklmnopqrstuvwxyz'.split('');
   const map = getMap(legend, shift);
   return str
   .toLowerCase()
   .split('')
   .map(char => map[char] || char)
   .join('');
};
console.log(encrypt(str, 6));

Output

Following is the output on console −

znoyoygyzxotm
raja
Published on 11-Dec-2020 09:10:27
Advertisements