|
| 1 | +// libUUID v0.0.1 by GUD Team | Tired of copying and pasting a UUID function over and over? Me too. This script provides a couple of functions to generate UUIDs. |
| 2 | +class libUUID { |
| 3 | + static base64Chars = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; |
| 4 | + static base = 64; |
| 5 | + static previousTime = 0; |
| 6 | + static counter = new Array(12).fill(0); |
| 7 | + static toBase64(num, length) { |
| 8 | + let result = ""; |
| 9 | + for (let i = 0; i < length; i++) { |
| 10 | + result = this.base64Chars[num % this.base] + result; |
| 11 | + num = Math.floor(num / this.base); |
| 12 | + } |
| 13 | + return result; |
| 14 | + } |
| 15 | + ; |
| 16 | + static generateRandomBase64(length) { |
| 17 | + let result = ""; |
| 18 | + for (let i = 0; i < length; i++) { |
| 19 | + result += this.base64Chars[Math.floor(Math.random() * this.base)]; |
| 20 | + } |
| 21 | + return result; |
| 22 | + } |
| 23 | + ; |
| 24 | + static generateUUID() { |
| 25 | + const currentTime = Date.now(); |
| 26 | + const timeBase64 = this.toBase64(currentTime, 8); |
| 27 | + let randomOrCounterBase64 = ""; |
| 28 | + if (currentTime === this.previousTime) { |
| 29 | + // Increment the counter |
| 30 | + for (let i = this.counter.length - 1; i >= 0; i--) { |
| 31 | + this.counter[i]++; |
| 32 | + if (this.counter[i] < this.base) { |
| 33 | + break; |
| 34 | + } |
| 35 | + else { |
| 36 | + this.counter[i] = 0; |
| 37 | + } |
| 38 | + } |
| 39 | + randomOrCounterBase64 = this.counter.map(index => this.base64Chars[index]).join(""); |
| 40 | + } |
| 41 | + else { |
| 42 | + // Generate new random values and initialize counter with random starting values |
| 43 | + randomOrCounterBase64 = this.generateRandomBase64(12); |
| 44 | + // Initialize counter with random values instead of zeros to avoid hyphen-heavy sequences |
| 45 | + for (let i = 0; i < this.counter.length; i++) { |
| 46 | + this.counter[i] = Math.floor(Math.random() * this.base); |
| 47 | + } |
| 48 | + this.previousTime = currentTime; |
| 49 | + } |
| 50 | + return timeBase64 + randomOrCounterBase64; |
| 51 | + } |
| 52 | + ; |
| 53 | + static generateRowID() { |
| 54 | + return this.generateUUID().replace(/_/g, "Z"); |
| 55 | + } |
| 56 | + ; |
| 57 | +} |
0 commit comments