Exercise 16: Generate UUID v4 (simple)
Problem Statement
Create a function `generateUUID()` that generates a UUID v4 format string.
Example: generateUUID() → "550e8400-e29b-41d4-a716-446655440000" (format)
Sample Output:
generateUUID() => "550e8400-e29b-41d4-a716-446655440000" (format, random) generateUUID() => "a1b2c3d4-e5f6-4789-a012-b3c4d5e6f789" (format, random)
Solution
const generateUUID = () => {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};Explanation
Overall Goal:
- UUID v4 (random UUID) generate karna.
- Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx.
Line 1: Function header
const generateUUID = () => {
Line 2: Template replacement
"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, ...)- Template string me x aur y ko replace.
Line 3: Random hex digit
const r = (Math.random() * 16) | 0;- 0-15 ke beech random integer.
Line 4: Version/variant bits
const v = c === "x" ? r : (r & 0x3) | 0x8;- "x" → random hex.
- "y" → variant bits set (8, 9, A, B).
Line 5: Convert to hex
return v.toString(16);
Real world:
- Database IDs: unique identifiers.
- Session tokens: unique session IDs.
- File uploads: unique filenames.