Generate UUID
Generates a random UUID (Universally Unique Identifier).
snippets/typescript/generate-uuid.ts
/**
* Generates a random UUID (Universally Unique Identifier).
*
* @returns {string} The generated UUID.
*/
export const generateUUID = () => {
let uuid = "";
const chars = "0123456789abcdef";
for (let i = 0; i < 36; i++) {
if (i === 8 || i === 13 || i === 18 || i === 23) {
uuid += "-";
} else if (i === 14) {
uuid += "4";
} else if (i === 19) {
uuid += chars.charAt(Math.random() * chars.length);
} else {
uuid += chars.charAt(Math.random() * chars.length);
}
}
return uuid;
};
Examples
snippets/typescript/generate-uuid.example.ts
import { generateUUID } from "./generate-uuid";
generateUUID(); // db910787-ee2f-4170-0b6e-a0000f6df47b
Tests
snippets/typescript/generate-uuid.test.ts
import { describe } from "bun:test";
describe.todo("generateUuid", () => {});