-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
103 lines (70 loc) · 2.76 KB
/
Copy pathindex.js
File metadata and controls
103 lines (70 loc) · 2.76 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var random = require('./random');
var repeat = require('repeat-string');
function digits(value, bytes) {
// Converts the value to a string binary representation
var binValueStr = value.toString(2);
// Generate an string with zero values
var zeroPad = repeat('0000', bytes);
// Pad the binary value withe the zeros on the left
binValueStr = zeroPad + binValueStr;
// Take N bytes from the right, adding a '1' on the left
binValueStr = '1' + binValueStr.substring(binValueStr.length - (4 * bytes), binValueStr.length);
return parseInt(binValueStr, 2).toString(16).substring(1);
}
function getTimeBasedBlocks(millis, addNanos) {
// Convert millis to nanos
var nanos = millis * 10000;
// Add random nanoseconds
if (addNanos !== 0) {
nanos += addNanos;
}
// Convert the nanos to binary string
var nanosBinString = nanos.toString(2);
// Get firts block
var timeBasedBlockValue = digits(parseInt(nanosBinString.substring(0, nanosBinString.length - 32), 2), 8);
timeBasedBlockValue += '-';
// Get second block
timeBasedBlockValue += digits(parseInt(nanosBinString.substring(0, nanosBinString.length - 16), 2), 4);
timeBasedBlockValue += '-';
// Get third block: Random part
timeBasedBlockValue += digits(parseInt(nanosBinString, 2), 4);
return timeBasedBlockValue;
}
exports.UUID1 = function() {
// Get the current millis
var millis = Date.now();
// Return the value
return exports.fromMillisUUID1(millis);
}
exports.fromMillisUUID1 = function(millis) {
// Generate the time based blocks adding a random number of nanoseconds
var uuidString = getTimeBasedBlocks(millis, random.randomInt(0, 10000));
uuidString += '-';
// Convert millis to nanos
var nanos = millis * 10000;
// Add random nanoseconds
var randomNanos = random.randomInt(0, 10000);
nanos += randomNanos;
// Convert the nanos to binary string
var nanosBinString = nanos.toString(2);
// Get forth block
uuidString += digits(parseInt(nanosBinString, 2), 4);
uuidString += '-';
// Get ffith block
uuidString += digits(parseInt(nanosBinString, 2), 12);
return uuidString;
}
exports.maxUUID1 = function(millis) {
// Generate the time based blocks
var uuidString = getTimeBasedBlocks(millis, 9999);
// Add the forth and fifth blocks
uuidString += '-ffff-ffffffffffff';
return uuidString;
}
exports.minUUID1 = function(millis) {
// Generate the time based blocks
var uuidString = getTimeBasedBlocks(millis, 0);
// Add the forth and fifth blocks
uuidString += '-0000-000000000000';
return uuidString;
}