randomPassword()
💾 replit
// ⭐️ 預設密碼長度: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('');
};
Last updated