create a password with at least one symbol in typescript

Here's an example function that generates a password with at least one symbol:

index.ts
function generatePassword(length: number): string {
  const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>/?';
  let password = '';

  while (password.length < length) {
    const charIndex = Math.floor(Math.random() * symbols.length);
    password += symbols.charAt(charIndex);
  }

  return password;
}
295 chars
12 lines

This function takes a desired length for the password as an argument and generates a random password containing only symbols from the symbols string. The while loop keeps adding symbols to the password until it reaches the desired length.

You can adjust the symbols string to include any symbols you want to allow in the password.

If you want to ensure that the password also includes letters and numbers, you can modify the function to generate a mixed password like this:

index.ts
function generatePassword(length: number): string {
  const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>/?';
  const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numbers = '0123456789';

  let password = '';
  password += getRandomChar(symbols);
  password += getRandomChar(letters);
  password += getRandomChar(numbers);

  while (password.length < length) {
    const charSet = [symbols, letters, numbers][Math.floor(Math.random() * 3)];
    password += getRandomChar(charSet);
  }

  return shuffleString(password);
}

function getRandomChar(charSet: string): string {
  const charIndex = Math.floor(Math.random() * charSet.length);
  return charSet.charAt(charIndex);
}

function shuffleString(str: string): string {
  const shuffled = str.split('').sort(function() {
    return 0.5 - Math.random();
  }).join('');
  
  return shuffled;
}
864 chars
31 lines

This function uses three separate sets of characters (symbols, letters, and numbers) to ensure that the password contains at least one of each type. The while loop then adds random characters from any of the three sets until the password reaches the desired length. The shuffleString function shuffles the order of the characters in the final password for added security.

gistlibby LogSnag