Skip to content

Instantly share code, notes, and snippets.

@htkcodes
Created November 23, 2017 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htkcodes/deb6b330758ee4c26d4a3363442642d3 to your computer and use it in GitHub Desktop.
Save htkcodes/deb6b330758ee4c26d4a3363442642d3 to your computer and use it in GitHub Desktop.
/*jshint esversion: 6 */
/*
Caesar Cipher is one of the earliest and simplest encryption technique. To encrypt a message, we shift the alphabets of the message by a fixed position or key.
For example, if message is ABC , and we shift each character by 3 characters, we will get DEF. Here key is 3.
*/
caesarCipher('Javascript',1);
function caesarCipher(string, number) {
number %= 26;
for (let lowerCaseString = string.toLowerCase(), alphabet = "abcdefghijklmnopqrstuvwxyz".split(""), shiftedString = "", i = 0; i < lowerCaseString.length; i++) {
let curLetter = lowerCaseString[i];
" " === curLetter ? shiftedString += curLetter : (curLetter = alphabet.indexOf(curLetter) + number, 25 < curLetter && (curLetter -= 26), 0 > curLetter && (curLetter += 26), shiftedString += alphabet[curLetter]);
}
console.log("Original Word: " + string + "\nNew String Shifted by " + number + " place: " + shiftedString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment