/** * Utility functions for generating and validating room codes. * * Room codes are 6 uppercase ASCII letters (A-Z). They are generated from a * combination of the current timestamp and a random component so that codes * are effectively unique without requiring a server round-trip. */ const ROOM_CODE_LENGTH = 6; const ROOM_CODE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const ROOM_CODE_REGEX = /^[A-Z]{6}$/; /** * Generates a 6-character uppercase room code. * * The code is derived from `Date.now()` combined with `Math.random()` so that * two codes generated at different times (or by different clients at the same * millisecond) are extremely unlikely to collide. */ export function generateRoomCode(): string { const seed = Date.now() + Math.floor(Math.random() * 1_000_000); let code = ""; let remaining = seed; for (let i = 0; i < ROOM_CODE_LENGTH; i++) { // Mix in additional randomness per character to avoid sequential patterns const idx = (remaining + Math.floor(Math.random() * ROOM_CODE_CHARS.length)) % ROOM_CODE_CHARS.length; code += ROOM_CODE_CHARS[idx]; remaining = Math.floor(remaining / ROOM_CODE_CHARS.length) + Date.now(); } return code; } /** * Returns true when `code` is a syntactically valid room code (exactly 6 * uppercase ASCII letters). */ export function isValidRoomCode(code: string): boolean { return ROOM_CODE_REGEX.test(code); }