-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
53 lines (45 loc) · 1.12 KB
/
index.js
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
/*!
* Module dependencies.
*/
var bignum = require('bignum');
/**
* The offset from which druuid UUIDs are generated (in milliseconds).
*/
exports.epoch = 0;
/**
* Generates a time-sortable, 64-bit UUID.
*
* Examples:
*
* druuid.gen()
* // => <BigInt 11142943683383068069>
*
* @param {Date} [date=new Date()] of UUID
* @param {Number} [epoch=druuid.epoch] offset
* @return {BigInt} UUID
* @public
*/
exports.gen = function gen(date, epoch){
if (!date) date = new Date();
if (!epoch) epoch = exports.epoch;
var id = bignum(date - epoch).shiftLeft(64 - 41);
return id.or(Math.round(Math.random() * 1e16) % Math.pow(2, 64 - 41));
};
/**
* Determines when a given UUID was generated.
*
* Examples:
*
* druuid.time(11142943683383068069);
* // => Sat Feb 04 2012 00:00:00 GMT-0800 (PST)
*
* @param {BigInt|Number|String} uuid
* @param {Number} [epoch=druuid.epoch] offset
* @return {Date} when UUID was generated
* @public
*/
exports.time = function(uuid, epoch){
if (!epoch) epoch = exports.epoch;
var ms = bignum(uuid).shiftRight(64 - 41).toNumber();
return new Date(ms + epoch);
};