-
Notifications
You must be signed in to change notification settings - Fork 123
/
index.js
84 lines (68 loc) · 2.18 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
/**
* cuid.js
* Collision-resistant UID generator for browsers and node.
* Sequential for fast db lookups and recency sorting.
* Safe for element IDs and server-side lookups.
*
* Extracted from CLCTR
*
* Copyright (c) Eric Elliott 2012
* MIT License
*/
var fingerprint = require('./lib/fingerprint.js');
var pad = require('./lib/pad.js');
var getRandomValue = require('./lib/getRandomValue.js');
var c = 0,
blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize);
function randomBlock () {
return pad((getRandomValue() *
discreteValues << 0)
.toString(base), blockSize);
}
function safeCounter () {
c = c < discreteValues ? c : 0;
c++; // this is not subliminal
return c - 1;
}
function cuid () {
// Starting with a lowercase letter makes
// it HTML element ID friendly.
var letter = 'c', // hard-coded allows for sequential access
// timestamp
// warning: this exposes the exact date and time
// that the uid was created.
timestamp = (new Date().getTime()).toString(base),
// Prevent same-machine collisions.
counter = pad(safeCounter().toString(base), blockSize),
// A few chars to generate distinct ids for different
// clients (so different computers are far less
// likely to generate the same id)
print = fingerprint(),
// Grab some more chars from Math.random()
random = randomBlock() + randomBlock();
return letter + timestamp + counter + print + random;
}
cuid.slug = function slug () {
var date = new Date().getTime().toString(36),
counter = safeCounter().toString(36).slice(-4),
print = fingerprint().slice(0, 1) +
fingerprint().slice(-1),
random = randomBlock().slice(-2);
return date.slice(-2) +
counter + print + random;
};
cuid.isCuid = function isCuid (stringToCheck) {
if (typeof stringToCheck !== 'string') return false;
if (stringToCheck.startsWith('c')) return true;
return false;
};
cuid.isSlug = function isSlug (stringToCheck) {
if (typeof stringToCheck !== 'string') return false;
var stringLength = stringToCheck.length;
if (stringLength >= 7 && stringLength <= 10) return true;
return false;
};
cuid.fingerprint = fingerprint;
module.exports = cuid;