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