-
Notifications
You must be signed in to change notification settings - Fork 599
Expand file tree
/
Copy pathindex.ts
More file actions
59 lines (52 loc) · 1.58 KB
/
Copy pathindex.ts
File metadata and controls
59 lines (52 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const base64Chars = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
const base = 64;
let previousTime = 0;
const counter = new Array(12).fill(0);
function toBase64(num: number, length: number): string {
let result = "";
for (let i = 0; i < length; i++) {
result = base64Chars[num % base] + result;
num = Math.floor(num / base);
}
return result;
}
function generateRandomBase64(length: number): string {
let result = "";
for (let i = 0; i < length; i++) {
result += base64Chars[Math.floor(Math.random() * base)];
}
return result;
}
function generateUUID(): string {
const currentTime = Date.now();
const timeBase64 = toBase64(currentTime, 8);
let randomOrCounterBase64 = "";
if (currentTime === previousTime) {
// Increment the counter
for (let i = counter.length - 1; i >= 0; i--) {
counter[i]++;
if (counter[i] < base) {
break;
} else {
counter[i] = 0;
}
}
randomOrCounterBase64 = counter.map(index => base64Chars[index]).join("");
} else {
// Generate new random values and initialize counter with random starting values
randomOrCounterBase64 = generateRandomBase64(12);
// Initialize counter with random values instead of zeros to avoid hyphen-heavy sequences
for (let i = 0; i < counter.length; i++) {
counter[i] = Math.floor(Math.random() * base);
}
previousTime = currentTime;
}
return timeBase64 + randomOrCounterBase64;
}
function generateRowID(): string {
return generateUUID().replace(/_/g, "Z");
}
export default {
generateUUID,
generateRowID,
};