@bugsnag/cuid
Version:
Collision-resistant ids optimized for horizontal scaling and performance. For node and browsers.
68 lines (52 loc) • 1.71 kB
JavaScript
const isCuid = require('./is-cuid.js');
const pad = require('./pad.js');
/**
* 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
*/
function createCuid (fingerprint) {
const blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize);
let c = 0;
function randomBlock () {
return pad((Math.random() *
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.fingerprint = fingerprint;
cuid.isCuid = isCuid;
return cuid;
}
module.exports = createCuid;
;