Skip to content

Instantly share code, notes, and snippets.

@clehner
Created April 24, 2011 05:53
Show Gist options
  • Save clehner/939361 to your computer and use it in GitHub Desktop.
Save clehner/939361 to your computer and use it in GitHub Desktop.
Access Code Generator & Validator
// Access Code Generator & Validator
// API:
// string generateAccessCode()
// Boolean validateAccessCode(codeString)
(function () {
// configure:
var difference = 5;
var length = 12;
function startInt() {
return Math.random() * 36 >> 0;
}
function nextInt(n) {
var options = Math.ceil((36 - n) / difference);
if (n < difference) options--;
var a = n + Math.ceil(Math.random() * options) * difference;
return a % 36;
}
function nextIntCanBe(curr, next) {
var d = next - curr;
if (d < 0) d += 36;
return (d % difference) == 0;
}
function intToChar(i) {
return String.fromCharCode(i + (i < 10 ? 48 : 55));
//65-90 are LETTERS
//48-57 are numbers
}
function charToInt(c) {
var n = c.charCodeAt(0);
return n - (n < 65 ? 48 : 55);
}
generateAccessCode = function () {
var chars = new Array(length);
var r = startInt();
for (var i = 0; i < length; i++) {
r = nextInt(r);
chars[i] = intToChar(r);
}
return chars.join("");
}
validateAccessCode = function (code) {
if (code.length != length) {
return false;
}
code = code.toUpperCase();
var r = charToInt(code[0]);
for (var i = 1; i < code.length - 1; i++) {
if (!nextIntCanBe(r), r = charToInt(code[i])) {
return false;
}
}
return true;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment