create a password with a custom length and uppercase letters in typescript

Here's a simple implementation of a password generator function in TypeScript that takes in a desired length and generates a random password with uppercase letters:

index.ts
function generatePassword(length: number): string {
  const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const allChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let password = '';
  for (let i = 0; i < length; i++) {
    if (i === 0) {
      password += uppercaseChars.charAt(Math.floor(Math.random() * uppercaseChars.length));
    } else {
      password += allChars.charAt(Math.floor(Math.random() * allChars.length));
    }
  }
  return password;
}
485 chars
14 lines

This function first declares two strings: uppercaseChars which contains only uppercase letters, and allChars which contains uppercase letters, lowercase letters, and digits. It then initializes an empty string for the password.

The function then iterates length number of times and adds a random character from the uppercaseChars string for the first character, and from the allChars string for the rest of the characters. Finally, the function returns the generated password.

You can call this function with a desired length to generate a random password:

index.ts
const password = generatePassword(8); // generates an 8-character password with an uppercase first character
console.log(password); // outputs something like 'Z7j9Xz1F'
169 chars
3 lines

gistlibby LogSnag