Generate unique identifiers using various methods
1// Simple unique ID using timestamp and random
2function generateId() {
3 return Date.now().toString(36) + Math.random().toString(36).substring(2);
4}
5
6// UUID v4 (simplified)
7function generateUUID() {
8 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
9 const r = Math.random() * 16 | 0;
10 const v = c === 'x' ? r : (r & 0x3 | 0x8);
11 return v.toString(16);
12 });
13}
14
15// Short ID (URL-friendly)
16function generateShortId(length = 8) {
17 const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
18 let result = '';
19
20 for (let i = 0; i < length; i++) {
21 result += chars.charAt(Math.floor(Math.random() * chars.length));
22 }
23
24 return result;
25}
26
27// Nano ID (more collision-resistant)
28function generateNanoId(size = 21) {
29 const alphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
30 let id = '';
31
32 for (let i = 0; i < size; i++) {
33 id += alphabet[Math.floor(Math.random() * alphabet.length)];
34 }
35
36 return id;
37}
38
39// Usage examples
40console.log(generateId()); // "lh4j8k2m9n3o"
41console.log(generateUUID()); // "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
42console.log(generateShortId()); // "aB3xY9Qm"Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.