From e4f27b53edf45f3f2bfca21c86980b8c81b549c9 Mon Sep 17 00:00:00 2001 From: Douglas Barone Date: Tue, 30 Jan 2024 10:15:14 -0400 Subject: [PATCH] Refactor passwordGenerator function to use characterSets array --- web/src/utils/passwordGenerator.js | 51 +++++++++--------------------- 1 file changed, 15 insertions(+), 36 deletions(-) diff --git a/web/src/utils/passwordGenerator.js b/web/src/utils/passwordGenerator.js index 019c3bf..06e1b88 100644 --- a/web/src/utils/passwordGenerator.js +++ b/web/src/utils/passwordGenerator.js @@ -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