UNPKG

unique-usernames

Version:

unique-usernames is a lightweight and customizable npm package designed to generate unique and creative usernames for apps, organizations, and platforms. Whether you're building a social media app, a gaming platform, or any service that requires unique us

38 lines (37 loc) 1.68 kB
import { quirkyAdjectives, quirkyNouns, marvelNouns, cartoonNouns, animeNouns, nfswAdjectives } from "./constant"; const genreAdjectives = { quirky: quirkyAdjectives, nfsw: nfswAdjectives, }; const genreNouns = { quirky: quirkyNouns, marvel: marvelNouns, cartoons: cartoonNouns, anime: animeNouns, }; export function generateUniqueUsername({ adjectiveGenre = "quirky", nounGenre = "quirky", serial, separator = false, shouldCapitalize = false, isUsernameTaken = () => false, } = {}) { const adjectives = genreAdjectives[adjectiveGenre]; const nouns = genreNouns[nounGenre]; const maxAttempts = 1000; // Limit attempts to avoid infinite loops let attempt = 0; let username; do { if (attempt >= maxAttempts) { throw new Error("Unable to generate a unique username after multiple attempts."); } const randomNumber = serial !== null && serial !== void 0 ? serial : Math.floor(Math.random() * 1000000); // Support up to 1M users const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)]; const randomNoun = nouns[Math.floor(Math.random() * nouns.length)]; const separatorChar = separator && Math.random() < 0.5 ? "_" : ""; username = `${randomAdjective}${separatorChar}${randomNoun}`; if (shouldCapitalize) { username = username .split(separatorChar) .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join(separatorChar); } username = `${username}${randomNumber}`; attempt++; } while (isUsernameTaken(username)); return username; }