33 lines
1.3 KiB
TypeScript
33 lines
1.3 KiB
TypeScript
let special = "!@$&*()_+";
|
|
let digits = "0123456789";
|
|
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
|
|
interface PasswordGeneratorConfiguration {
|
|
length?: number;
|
|
numberOfDigits?: number;
|
|
numberOfSpecialCharacters?: number;
|
|
}
|
|
|
|
export function generatePassword({ length = 16, numberOfDigits = 2, numberOfSpecialCharacters = 4 }: PasswordGeneratorConfiguration): string {
|
|
let password = "";
|
|
|
|
for (let i = 0; i < length - numberOfDigits - numberOfSpecialCharacters; i++) {
|
|
const randomIndex = Math.floor(Math.random() * length);
|
|
const randomLetter = Math.floor(Math.random() * letters.length);
|
|
password = password.slice(0, randomIndex) + letters[randomLetter] + password.slice(randomIndex);
|
|
}
|
|
|
|
for (let i = 0; i < numberOfDigits; i++) {
|
|
const randomIndex = Math.floor(Math.random() * length);
|
|
const randomDigit = Math.floor(Math.random() * 10);
|
|
password = password.slice(0, randomIndex) + digits[randomDigit] + password.slice(randomIndex);
|
|
}
|
|
|
|
for (let i = 0; i < numberOfSpecialCharacters; i++) {
|
|
const randomIndex = Math.floor(Math.random() * length);
|
|
const randomSpecial = Math.floor(Math.random() * special.length);
|
|
password = password.slice(0, randomIndex) + special[randomSpecial] + password.slice(randomIndex);
|
|
}
|
|
|
|
return password;
|
|
} |