UNPKG

2.75 kBJavaScriptView Raw
1/*
2 * Short Id
3 * by Dylan Greene
4 */
5
6var alphabet = require('./lib/alphabet'),
7 encode = require('./lib/encode');
8
9// Ignore all milliseconds before shortID was created to reduce the size of the date entropy
10// without sacrificing uniqueness. This number can be updated if we also bump the version below.
11var REDUCE_TIME = 1374349322543;
12
13// don't change unless we change the algos or REDUCE_TIME
14// must be an integer and less than 16
15var version = 1;
16
17// if you are using cluster or multiple servers use this to make each instance
18// has a unique value for worker
19var clusterWorkerId = parseInt(process.env.NODE_UNIQUE_ID || 0, 10);
20
21// Counter is used when shortId is called multiple times in one second.
22var counter;
23
24// Remember the last time shortId was called in case counter is needed.
25var previousSeconds;
26
27
28/**
29 * Generate unique id
30 * Returns string id
31 */
32function generate() {
33
34 var str = '';
35
36 var seconds = Math.round((Date.now() - REDUCE_TIME) * 0.01);
37
38 if (seconds == previousSeconds) {
39 counter++;
40 } else {
41 counter = 0;
42 previousSeconds = seconds;
43 }
44
45 str = str + encode(alphabet.lookup, version);
46 str = str + encode(alphabet.lookup, clusterWorkerId);
47 if (counter > 0) {
48 str = str + encode(alphabet.lookup, counter);
49 }
50 str = str + encode(alphabet.lookup, seconds);
51
52 return str;
53}
54
55
56/**
57 * Set the seed.
58 * Highly recommended if you don't want people to try to figure out your id schema.
59 * exposed as ShortId.seed(int)
60 * @param seed Integer value to seed the random alphabet. ALWAYS USE THE SAME SEED or you might get overlaps.
61 */
62function seed(seed) {
63 alphabet.seed(seed);
64 return module.exports;
65}
66
67/**
68 * Set the cluster worker or machine id
69 * exposed as ShortId.worker(int)
70 * @param workerId worker must be positive integer. Number less than 16 is recommended.
71 * returns ShortId module so it can be chained.
72 */
73function worker(workerId) {
74 clusterWorkerId = workerId;
75 return module.exports;
76}
77
78/**
79 *
80 * returns the shuffled alphabet
81 */
82function characters(newCharacters) {
83 if (newCharacters !== undefined) {
84 alphabet.characters(newCharacters);
85 }
86
87 return alphabet.shuffled();
88}
89
90/**
91 * Decode the id to get the version and worker
92 * Mainly for debugging and testing.
93 * @param id - the ShortId-generated id.
94 */
95function decode(id) {
96 var alphabet = characters();
97 return {
98 version: alphabet.indexOf(id.substr(0, 1)) & 0x0f,
99 worker: alphabet.indexOf(id.substr(1, 1)) & 0x0f
100 };
101}
102
103module.exports = generate;
104module.exports.generate = generate;
105module.exports.seed = seed;
106module.exports.worker = worker;
107module.exports.characters = characters;
108module.exports.decode = decode;
\No newline at end of file