Refactor passwordGenerator function to use characterSets array

This commit is contained in:
Douglas Barone 2024-01-30 10:15:14 -04:00
parent 25cf3f103f
commit e4f27b53ed

View File

@ -2,49 +2,28 @@
// containing at least one lowercase letter, one uppercase letter, one number, and one special character
export function passwordGenerator(length = 8) {
// Define character sets
const lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz'
const upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const numbers = '0123456789'
// const specialCharacters = '!@#$%&*()[]{}/'
// Initialize character set
let characterSet = ''
const characterSets = [
'abcdefghijklmnopqrstuvwxyz', // Lowercase letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZ', // Uppercase letters
'0123456789' // Numbers
// '!@#$%&*()[]{}' // Special characters
]
// Initialize password
let password = ''
// Add a lowercase letter to the character set
characterSet += lowerCaseLetters
// Pick a random lowercase letter and add it to the password
password += lowerCaseLetters.charAt(
Math.floor(Math.random() * lowerCaseLetters.length)
)
// Add an uppercase letter to the character set
characterSet += upperCaseLetters
// Pick a random uppercase letter and add it to the password
password += upperCaseLetters.charAt(
Math.floor(Math.random() * upperCaseLetters.length)
)
// Add a number to the character set
characterSet += numbers
// Pick a random number and add it to the password
password += numbers.charAt(Math.floor(Math.random() * numbers.length))
// Add a special character to the character set
// characterSet += specialCharacters
// Pick a random special character and add it to the password
// password += specialCharacters.charAt(
// Math.floor(Math.random() * specialCharacters.length)
// )
// Pick a random character from each character set and add it to the password
characterSets.forEach(set => {
password += set.charAt(Math.floor(Math.random() * set.length))
})
// Add random characters to the password until it reaches the desired length
for (let i = 3; i < length; i++) {
password += characterSet.charAt(
Math.floor(Math.random() * characterSet.length)
const flatCharacterSets = characterSets.join('')
for (let i = characterSets.length; i < length; i++)
password += flatCharacterSets.charAt(
Math.floor(Math.random() * flatCharacterSets.length)
)
}
// Shuffle the password
password = password