/** * Generate a UUID v4 */ export function generateUUID(): string { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } /** * Generate a deterministic UUID from a string * This ensures the same input always produces the same UUID */ export function generateDeterministicUUID(input: string): string { // Simple hash function to convert string to number let hash = 0; for (let i = 0; i < input.length; i++) { const char = input.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; // Convert to 32bit integer } // Convert hash to UUID format const hex1 = Math.abs(hash).toString(16).padStart(8, '0'); // Generate additional deterministic hex strings for different UUID segments let hash2 = hash; for (let i = 0; i < input.length; i++) { hash2 = ((hash2 << 3) + input.charCodeAt(i)) & 0xFFFFFFFF; } const hex2 = Math.abs(hash2).toString(16).padStart(8, '0'); // Generate third hash for the 12-character segment let hash3 = hash2; for (let i = 0; i < input.length; i++) { hash3 = ((hash3 << 7) + input.charCodeAt(input.length - 1 - i)) & 0xFFFFFFFF; } const hex3 = Math.abs(hash3).toString(16).padStart(8, '0'); // Combine to make more hex data for segment 5 (needs 12 chars) const hex3_extended = (hex3 + hex1).substring(0, 12); // Create UUID v4 format (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) // Segment 1: 8 hex chars // Segment 2: 4 hex chars // Segment 3: 4 hex chars (starting with '4' for version 4) // Segment 4: 4 hex chars (should start with 8, 9, a, or b for variant) // Segment 5: 12 hex chars const segment4 = hex2.substring(0, 4); const segment4Fixed = (parseInt(segment4.charAt(0), 16) & 0x3 | 0x8).toString(16) + segment4.substring(1, 4); return `${hex1.substring(0, 8)}-${hex1.substring(0, 4)}-4${hex1.substring(4, 7)}-${segment4Fixed}-${hex3_extended}`; } /** * Generate a simple numeric hash from a string */ export function hashString(str: string): number { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; // Convert to 32bit integer } return Math.abs(hash); }