create a password with numbers in typescript

To create a password with numbers in TypeScript, we can use the crypto module that comes with Node.js. Here's an example:

index.ts
import { randomBytes } from "crypto";

function generatePassword(length: number): string {
  const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  const charsCount = chars.length;

  const randomBytesCount = Math.ceil((length * 3) / 4);
  const randomBytesValue = randomBytes(randomBytesCount);

  let password = "";
  let charIndex = 0;

  for (let i = 0; i < length; i++) {
    if (i % 4 === 0) {
      charIndex = randomBytesValue.readUInt8(i / 4) % charsCount;
    }
    password += chars[charIndex];
    charIndex = Math.floor(charIndex / charsCount);
  }

  return password;
}

// Usage example
console.log(generatePassword(10)); // Output: "3rPQ6d8atv"
688 chars
26 lines

This code generates a random password containing lowercase and uppercase letters and digits. The length of the password is specified as an argument to the generatePassword function. The function uses the randomBytes function from the crypto module to generate a random sequence of bytes, which is then mapped to the character set by taking 3 bits at a time. The resulting password is returned as a string.

gistlibby LogSnag