30 lines
998 B
TypeScript
30 lines
998 B
TypeScript
export const generatePassword = (length = 10) => {
|
|
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
const lower = "abcdefghijklmnopqrstuvwxyz";
|
|
const numbers = "0123456789";
|
|
const special = "!@#$%^&*()_+[]{}<>?/|";
|
|
|
|
// Ensure at least one from each required set
|
|
const required = [
|
|
upper[Math.floor(Math.random() * upper.length)],
|
|
lower[Math.floor(Math.random() * lower.length)],
|
|
numbers[Math.floor(Math.random() * numbers.length)],
|
|
special[Math.floor(Math.random() * special.length)],
|
|
];
|
|
|
|
const allChars = upper + lower + numbers + special;
|
|
const remainingLength = length - required.length;
|
|
const passwordArr = [...required];
|
|
|
|
for (let i = 0; i < remainingLength; i++) {
|
|
passwordArr.push(allChars[Math.floor(Math.random() * allChars.length)]);
|
|
}
|
|
|
|
// Fisher-Yates shuffle
|
|
for (let i = passwordArr.length - 1; i > 0; i--) {
|
|
const j = Math.floor(Math.random() * (i + 1));
|
|
[passwordArr[i], passwordArr[j]] = [passwordArr[j], passwordArr[i]];
|
|
}
|
|
|
|
return passwordArr.join("");
|
|
};
|