forked from ulid/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (73 loc) · 1.77 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
(function(_window) {
"use strict";
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
var ENCODING_LEN = ENCODING.length
var TIME_LEN = 10
var RANDOM_LEN = 16
var prng
if (_window) {
try {
var crypto = _window.crypto || _window.msCrypto
prng = function() {
return crypto.getRandomValues(new Uint16Array(1))[0] / 0xFFFF
}
}
catch(e) {}
}
else {
try {
var crypto = require("crypto")
prng = function() {
return crypto.randomBytes(2).readUInt16LE() / 0xFFFF
}
}
catch(e) {}
}
if (typeof prng !== "function") {
prng = function() {
return Math.random()
}
if (typeof console !== "undefined" && console.warn) {
console.warn("[ulid] crypto not usable, falling back to insecure Math.random()");
}
}
function encodeTime(now, len) {
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
if (("undefined" !== typeof module) && module.exports) {
module.exports = ulid
}
else if (typeof define === "function" && define.amd) {
define(function() {
return ulid;
})
}
else {
_window.ulid = ulid
}
})("undefined" !== typeof window ? window : null)