Skip to content

Instantly share code, notes, and snippets.

@htmelvis
Created July 5, 2015 13:03
Show Gist options
  • Save htmelvis/309ed2fcdf23d087f846 to your computer and use it in GitHub Desktop.
Save htmelvis/309ed2fcdf23d087f846 to your computer and use it in GitHub Desktop.
Simple ROT13 Cypher for JS
var Decipher = function(text, rot){
var lookup = ["a","b","c","d","e","f","g","h","i","j",
"k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z"];
//clone the original lookup table to make a new one
var newLookup = lookup.slice(0);
//This is the offset to go off of
var offset = rot;
//split the message into characters to check against table but lowercase all chars first
var msg = text.toLowerCase().split('');
//New end of the lookup array
var newEndLookup = newLookup.splice(0, offset);
//put the new reordered lookup together for the comparison
var newLookup = newLookup.concat(newEndLookup);
//loop through the msg using lookup tables to find new chars and build array of them
var decoded = [];
msg.forEach(function(element, index){
//Get the offset position of the character
var pos = newLookup.indexOf(element);
//Lookup the actual position in the character lookup table
var newElement = lookup[pos];
//If it isnt an empty space character
if(pos !== -1){
decoded.push(newElement);
} else {
decoded.push(" ");
}
});
//Join the decoded array back into a string
var decodedMsg = decoded.join('');
console.log("Original Message: " + text);
console.log("The ROT Type: " + rot);
console.log("The Decoded Message: " + decodedMsg);
return {
ogMsg: text,
rotType: rot,
decodedMsg: decodedMsg
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment