generate a password of 8 characters that contains at least one uppercase letter, one lowercase letter, and one number in typescript

index.ts
function generatePassword(): string {
  const length = 8;
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const lowercase = 'abcdefghijklmnopqrstuvwxyz';
  const numbers = '0123456789';
  const chars = `${uppercase}${lowercase}${numbers}`; // Combine all possible characters
  let password = '';
  let hasUppercase = false;
  let hasLowercase = false;
  let hasNumber = false;

  // Generate a random character from the combined characters and add it to password
  for (let i = 0; i < length; i++) {
    const randomChar = chars[Math.floor(Math.random() * chars.length)];
    password += randomChar;

    // Check if the character is uppercase, lowercase or a number and set the corresponding flag to true
    if (uppercase.includes(randomChar)) {
      hasUppercase = true;
    } else if (lowercase.includes(randomChar)) {
      hasLowercase = true;
    } else if (numbers.includes(randomChar)) {
      hasNumber = true;
    }
  }

  // If any of the required character types are missing, generate a new password recursively
  if (!hasUppercase || !hasLowercase || !hasNumber) {
    password = generatePassword();
  }

  return password;
}
1145 chars
34 lines

The function generatePassword() generates a random password of length 8 that contains at least one uppercase letter, one lowercase letter, and one number. It uses a combination of uppercase letters, lowercase letters, and numbers to generate the password, and checks if it meets the criteria specified. If any of the required character types are missing, the function calls itself recursively until it generates a password that meets the requirements. The function returns the generated password as a string.

gistlibby LogSnag