randomPassword()
Last updated
Was this helpful?
Last updated
Was this helpful?
๐พ
// โญ๏ธ ้ ่จญๅฏ็ขผ้ทๅบฆ๏ผ32
function randomPassword(length = 32, {
digit = true, // ่ฆๆๆธๅญ
lowercase = true, // ่ฆๆๅฐๅฏซ
uppercase = true, // ่ฆๆๅคงๅฏซ
underscore = true, // ๅฏไปฅๆ "_"
symbol = true, // ็นๆฎ็ฌฆ่
}={}){
// 1. ๅญ้
let digits = String.fromCharCodesBetween(48, 57); // '0...9'
let letters = String.fromCharCodesBetween(97, 122); // 'a...z'
let capitals = String.fromCharCodesBetween(65, 90); // 'A...Z'
let symbols = "!@#$%^&*";
let underscores = "_";
// 2. ๆบๅ็ตๅๅฏ็ขผ
let pwd = ''; // ๅฏ็ขผ
let candidates = ''; // ๅฏ็ขผๅ้ธๅญ
// 3. ๅพๅฟ
็จ็ๅญ้ไธญ้ธๅญ
[
[digit, digits], // ๆธๅญ
[lowercase, letters], // ๅฐๅฏซ
[uppercase, capitals], // ๅคงๅฏซ
[underscore, underscores], // ๅบ็ท "_"
[symbol, symbols], // ็นๆฎ็ฌฆ่
].forEach(([include, chars]) => {
if(include){ // ๅฆๆ่ฆๅ ๅ
ฅ
pwd += chars.random(); // ๅ
ๅ ๅ
ฅไธๅๅญๅ
candidates += chars; // ๆด็ตๅญ้ๅ ๅ
ฅๅ้ธๅญ
}
});
// 4. ๅฆๆๅฏ็ขผ้ทๅบฆไธ่ถณ๏ผๅฐฑ็นผ็บ้ธๅญ
let k = pwd.length; // ็ฎๅๅฏ็ขผ้ทๅบฆ
let n = candidates.length; // ้ธ็จๅญ็ธฝ้ทๅบฆ
while(k < length){
pwd += candidates.random();
k += 1;
}
return pwd.shuffle();
}
const { log } = console;
const { floor, random: rand } = Math;
/* --------------- helpers --------------- */
// โญ๏ธ random int: 0 ... n-1
// randomInt(5): choose from 0, 1, 2, 3, 4
function randomInt(n){
return floor( n * rand() );
}
// โญ๏ธ array.random()
Array.prototype.random = function(){
return this[randomInt(this.length)];
};
// โญ๏ธ string.random()
// โญ๏ธ Note: this may not work well with Unicodeโ๏ธ
String.prototype.random = function(){
return this[randomInt(this.length)];
}
// โญ๏ธ string.shuffle()
String.prototype.shuffle = function(){
var a = this.split("");
var n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = randomInt(i+1);
[a[i], a[j]] = [a[j], a[i]];
}
return a.join("");
}
// โญ๏ธ String.fromCharCodesBetween(65, 70) -> 'ABCDEF'
String.fromCharCodesBetween = function(from, to){
let array = [];
for(let i = from; i <= to; i++) array.push(i);
return array
.map(code => String.fromCharCode(code))
.join('');
};