Last active
February 9, 2018 17:12
-
-
Save doubleOrt/795dd3ea566906a12ea14c8e21a7fc82 to your computer and use it in GitHub Desktop.
Vanilla JavaScript implementation of the Caesar Cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CaesarCipher = (function() { | |
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split(""); | |
const encrypt = function encrypt(msg, key) { | |
if ( !typeof msg == 'string' || !Number.isInteger(key) ) { | |
return false; | |
} | |
return Array.from(msg) | |
.map(function(el) { | |
el = el.toLowerCase(); | |
return alphabet.indexOf(el) === -1 ? el : alphabet[ | |
(alphabet.indexOf(el) + key) % alphabet.length | |
]; | |
}) | |
.join(""); | |
}; | |
const decrypt = function decrypt(msg, key) { | |
if ( !typeof msg == 'string' || !Number.isInteger(key) ) { | |
return false; | |
} | |
return Array.from(msg) | |
.map(function(el) { | |
elIndex = alphabet.indexOf(el); | |
alphLength = alphabet.length; | |
return elIndex === -1 ? el : alphabet[ | |
((elIndex % alphLength - key % alphLength) + alphLength) | |
% alphLength | |
]; | |
}) | |
.join(""); | |
}; | |
return { | |
encrypt: encrypt, | |
decrypt: decrypt | |
}; | |
})(); | |
// usage: | |
const msg = 'Gandalf and dwarves'; | |
const key = 2232; | |
console.log(CaesarCipher.encrypt(msg, key)); | |
console.log(CaesarCipher.decrypt(CaesarCipher.encrypt(msg, key), key)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment