Last active
August 29, 2015 14:15
-
-
Save citylims/106e55596bb9e0f7fc44 to your computer and use it in GitHub Desktop.
Warm-up JS exercise to start off the day - Vigenère 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
function encryptMessage(message, keyword) { | |
var cipher = []; | |
var alpha = 'abcdefghigklmnopqrstuvwxyz'.split(''); | |
var alphaLength = alpha.length; | |
//split input | |
var message = message.split(''); | |
var keyword = keyword.split(''); | |
//config for key position | |
var keyIndex = 0; | |
var keyLength = keyword.length; | |
//encode loop | |
for(var i=0; i < message.length; i++) { | |
//get message alpha index | |
var messageValue = alpha.indexOf(message[i]); | |
// get keyword alpha index | |
var keyValue = alpha.indexOf(keyword[keyIndex]); | |
//add the two | |
var charValue = (messageValue + keyValue); | |
//readjust if charValue is greater than alpha | |
//then assign char | |
if (charValue >= alphaLength){ | |
var char = alpha[(charValue - alphaLength)]; | |
} | |
// assign char that is less then alphalength | |
else { | |
var char = alpha[charValue]; | |
} | |
//reset the keyindex | |
if (++keyIndex >= keyLength){ | |
keyIndex = 0; | |
} | |
else { | |
keyIndex; | |
} | |
console.log(keyIndex); | |
//push character into cypher | |
cipher.push(char) | |
} | |
return cipher.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment