Last active
August 29, 2015 14:20
-
-
Save Pushplaybang/5fd32d4533fe4ee5c962 to your computer and use it in GitHub Desktop.
Javascript Rotation Cipher
This file contains hidden or 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
/* | |
Rotation Ciphers | |
*/ | |
var RotCipher = (function() { | |
var alpha = "abcdefghijklmnopqrstuvwxyz"; | |
var obj = { | |
result : "", | |
char : "", | |
pos : 0, | |
rotate : 0, | |
run : function decode(msg, rot) { | |
if (rot >= 26 || rot < 1) { | |
console.error('use a rotation less than 26, and greater than 1!'); | |
return false; | |
} | |
var self = this; | |
this.rotate = rot; | |
for (i = 0; i < msg.length; i++) { | |
self.char = msg.charAt(i); | |
self.getPosition().replaceChar(); | |
} | |
return this.result; | |
}, | |
getPosition : function getPosition() { | |
this.pos = alpha.indexOf(this.char.toLowerCase()) - this.rotate; | |
return this; | |
}, | |
replaceChar : function replaceChar() { | |
var ch = this.char; | |
var abc = (this.isUpperCase(ch)) ? alpha.toUpperCase() : alpha; | |
if (ch === " " || this.isNumber(ch) || this.isPunc(ch) ) { | |
this.result += ch; | |
return this; | |
} | |
if (this.pos < 0) { | |
this.result += abc.charAt(26+this.pos); | |
} else { | |
this.result += abc.charAt(this.pos); | |
} | |
return this; | |
}, | |
isNumber : function isNumber( char ) { | |
if ( typeof char !== "undefined" && !isNaN(parseInt( char)) ) { | |
return true; | |
} else if ( !isNaN(parseFloat( char)) ) { | |
return true; | |
} | |
return false; | |
}, | |
isPunc : function isPunc( char ) { | |
var puncReg = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#\$%&\(\)\*\+,\-\.\/:;<=>\?@\[\]\^_`\{\|\}~]/g; | |
if (puncReg.test(char)) { | |
return true; | |
} | |
return false; | |
}, | |
isUpperCase : function usUpperCase( char ) { | |
if ( char < 'a' ) { | |
return true; | |
} | |
return false; | |
} | |
}; | |
return obj; | |
})(); | |
var msg = RotCipher.run("Url zna, vz va gbja naq qbja ng gur cho univat svfu naq puvcf naq n orre. Whfg purpxvat lbh fgvyy unir gung frperg xrl v tnir lbh lrnef ntb! nyfb, vgf gvzr v gbyq lbh gur gehgu. Vz gur mbqvnp xvyyre, qbag gryy naq ab whqtvrf x?", 13); | |
console.log(msg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This rotates the given text by any number passed in as the second argument, so it can be used to encode and decode a simple rotation cipher, it handles uppercase letters, ignores both integers and floats, as well as punctuation.