DEV Community

Cover image for Caesar Cipher and JavaScript
Anas Nabil
Anas Nabil

Posted on

Caesar Cipher and JavaScript

What is Caesar Cipher?

In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, 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. The method is named after Julius Caesar, who used it in his private correspondence.


Code

const caesarCipher = (str, shift) => {
  const letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
  let res = '';

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

    if (ind === -1) {
      res += char;
      continue;
    }

    const encodedIndex = (ind + shift) % 26;
    res += letters[encodedIndex];
  }

  return res;
};
Enter fullscreen mode Exit fullscreen mode

Mocha Test

mocha.setup('bdd');
const { assert } = chai;

describe('caesarCipher()', () => {
  it('Shifting Letters Successfully', () => {
    assert.equal(caesarCipher('c', -2), 'a');
    assert.equal(caesarCipher('abcd', 1), 'bcde');
    assert.equal(caesarCipher('yz', 1), 'za');
    assert.equal(caesarCipher('abcd', 100), 'wxyz');
  });
  it("Doesn't shift non-alphabetic Characters", () => {
    assert.equal(caesarCipher('gurer ner 9 qbtf!', 13), 'there are 9 dogs!');
  });
});

mocha.run();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)