Skip to content

Instantly share code, notes, and snippets.

@Ptico
Last active December 23, 2015 04:59
Show Gist options
  • Save Ptico/6583891 to your computer and use it in GitHub Desktop.
Save Ptico/6583891 to your computer and use it in GitHub Desktop.
var Password = {},
utils;
function getOptionNum(target, defaults, rest) {
if (typeof(defaults) == 'undefined') defaults = 0;
var val = (typeof(target) == 'undefined') ? defaults : target;
if (val > rest) val = rest;
return val;
}
function getRest(rest, quant) {
var val = rest - quant;
return (val < 0) ? 0 : val;
}
Password.generate = function(length, options) {
var tmp = [],
defaults = Password.defaults,
nums, specials, uppers, lowers;
// Default values for arguments
if (typeof(length) == 'undefined') length = defaults.length;
if (length instanceof Array) length = utils.random(length[1], length[0]);
options = options || {};
// Assign quantity of different types
specials = getOptionNum(options.specials, defaults.specials, length);
length = getRest(length, specials);
nums = getOptionNum(options.nums, defaults.nums, length);
length = getRest(length, nums);
uppers = getOptionNum(options.uppers, defaults.uppers, length);
length = getRest(length, uppers);
lowers = getOptionNum(options.lowers, defaults.lowers, length);
length = getRest(length, lowers);
// Make an array of symbols
while(specials--) tmp.push(utils.special());
while(nums--) tmp.push(utils.num());
while(uppers--) tmp.push(utils.upperChar());
while(lowers--) tmp.push(utils.lowerChar());
while(length--) tmp.push(utils.anyChar());
// Shuffle the array and make a string
return utils.shuffle(tmp).join('');
}
Password.Utils = utils = {
num: function(num) {
return utils.random(9).toString();
},
upperChar: function() {
return utils.charFrom(Password.charsUpperCase);
},
lowerChar: function() {
return utils.charFrom(Password.charsLowerCase);
},
anyChar: function() {
return utils.charFrom(Password.charsLowerCase + Password.charsUpperCase);
},
special: function() {
return utils.charFrom(Password.specials);
},
charFrom: function(chars) {
return chars.charAt(utils.random(chars.length - 1));
},
random: function(max, min) {
if (typeof(min) == 'undefined') min = 0;
return Math.floor(Math.random() * (max - min + 1) + min);
},
// Fisher-Yates shuffle
shuffle: function(array) {
var i = array.length;
while (i--) {
var j = Math.floor(Math.random() * (i + 1)),
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
};
Password.specials = '~@#$%^&*()_-+=';
Password.charsLowerCase = 'abcdefghijklmnopqrstuvwxyz';
Password.charsUpperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Password.defaults = {
length: [7, 10],
specials: 1,
nums: 2,
uppers: 2,
lowers: 3
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment