AzLearn

تمرين إعادة البناء

Password Generator

أعد كتابة مولّد كلمات مرور TypeScript بإعدادات typed.

typescript ~10 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
// Run with: npx tsx 08-password-generator.ts (requires @types/node).
import { randomInt } from "node:crypto";

type PasswordOptions = {
  length: number;
  includeSymbols: boolean;
  includeNumbers: boolean;
};

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
const symbols = "!@#$%^&*";

function buildAlphabet(options: PasswordOptions): string {
  let alphabet = letters;

  if (options.includeNumbers) {
    alphabet += numbers;
  }
  if (options.includeSymbols) {
    alphabet += symbols;
  }

  return alphabet;
}

function generatePassword(options: PasswordOptions): string {
  const alphabet = buildAlphabet(options);
  let password = "";

  // randomInt is backed by /dev/urandom (or BCryptGenRandom on Windows) and
  // is the right primitive for security-sensitive choices like passwords.
  // Do NOT use the JS PRNG here — it is not cryptographically secure.
  for (let index = 0; index < options.length; index += 1) {
    const randomIndex = randomInt(0, alphabet.length);
    password += alphabet[randomIndex];
  }

  return password;
}

console.log(generatePassword({ length: 16, includeSymbols: true, includeNumbers: true }));
اكتب هنا