-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (40 loc) · 1018 Bytes
/
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
const mathRandom = require('math-random')
function pad(id) {
while ( id.length < 27 ) {
id += '0'
}
return id
}
function yid() {
let id = Date.now() + '-' + String(mathRandom()).substr(2, 13)
return pad(id)
}
function fromDate(d) {
let id = d.valueOf() + '-' + String(mathRandom()).substr(2, 13)
return pad(id)
}
function asDate(id) {
if ( !id.match(/^\d{13}-\d{13}$/) ) {
throw new Error(`yid.asDate(): Format of id is incorrect: ${id}`)
}
const epoch = id.split('-')[0]
return new Date(Number(epoch))
}
function asEpoch(id) {
if ( !id.match(/^\d{13}-\d{13}$/) ) {
throw new Error(`yid.asEpoch(): Format of id is incorrect: ${id}`)
}
const epoch = id.split('-')[0]
return Number(epoch)
}
function asRandom(id) {
if ( !id.match(/^\d{13}-\d{13}$/) ) {
throw new Error(`yid.asRandom(): Format of id is incorrect: ${id}`)
}
return id.split('-')[1]
}
yid.fromDate = fromDate
yid.asDate = asDate
yid.asEpoch = asEpoch
yid.asRandom = asRandom
module.exports = yid