forked from ulid/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (84 loc) · 1.97 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
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
"use strict";
function factory(prng) {
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
var ENCODING_LEN = ENCODING.length
var TIME_MAX = 281474976710655
var TIME_LEN = 10
var RANDOM_LEN = 16
function encodeTime(now, len) {
if (now > TIME_MAX) {
throw new Error("cannot encode time greater than " + TIME_MAX)
}
var mod
var now
var str = ""
for (var x = len; x > 0; x--) {
mod = now % ENCODING_LEN
str = ENCODING.charAt(mod) + str
now = (now - mod) / ENCODING_LEN
}
return str
}
function encodeRandom(len) {
var rand
var str = ""
for (var x = 0; x < len; x++) {
rand = Math.floor(ENCODING_LEN * prng())
str = ENCODING.charAt(rand) + str
}
return str
}
function ulid() {
return encodeTime(Date.now(), TIME_LEN) + encodeRandom(RANDOM_LEN)
}
ulid.prng = prng
ulid.encodeTime = encodeTime
ulid.encodeRandom = encodeRandom
return ulid
}
/* istanbul ignore next */
function _prng(root) {
if (root) {
try {
return function() {
return Math.random()
}
}
catch (e) {}
}
else {
try {
var randomBytes = require("randombytes")
return function() {
return randomBytes(2).readUInt16LE() / 0xFFFF
}
}
catch (e) {}
}
if (typeof prng !== "function") {
if (typeof console !== "undefined" && console.warn) {
console.warn("[ulid] crypto not usable, falling back to insecure Math.random()");
}
return function() {
return Math.random()
}
}
}
/* istanbul ignore next */
(function(root, fn) {
var prng = _prng(root)
var ulid = fn(prng)
if (("undefined" !== typeof module) && module.exports) {
module.exports = ulid
}
else if (typeof define === "function" && define.amd) {
define(function() {
return ulid
})
}
else {
root.ulid = ulid
}
})(typeof window !== "undefined" ? window : null, factory)