Generating a CUID (Collision-resistant Unique Identifier) in JavaScript involves using various techniques to ensure uniqueness, such as the current timestamp, a counter, a machine fingerprint, and randomness. Below is an example implementation of generating a CUID in JavaScript.
Steps to Generate a CUID in JavaScript
- Timestamp: Get the current timestamp in milliseconds.
- Counter: Use a counter to handle multiple CUIDs generated in a short period.
- Fingerprint: Generate a machine-specific fingerprint.
- Randomness: Add random characters to further reduce the risk of collisions.
- Base36 Encoding: Encode the components using Base36 for readability.
Example Code
const base36Chars = '0123456789abcdefghijklmnopqrstuvwxyz';
let counter = 0;
let lastTimestamp = 0;
function encodeBase36(value) {
let result = '';
while (value > 0) {
result = base36Chars[value % 36] + result;
value = Math.floor(value / 36);
}
return result;
}
function getMachineFingerprint() {
const crypto = require('crypto');
const os = require('os');
const hostname = os.hostname();
const hash = crypto.createHash('md5').update(hostname).digest('hex');
return hash.slice(0, 4);
}
function getRandomString(length) {
let result = '';
for (let i = 0; i < length; i++) {
result += base36Chars[Math.floor(Math.random() * 36)];
}
return result;
}
function generateCUID() {
const timestamp = Date.now();
if (timestamp === lastTimestamp) {
counter++;
} else {
lastTimestamp = timestamp;
counter = 0;
}
const timestampBase36 = encodeBase36(timestamp);
const counterBase36 = encodeBase36(counter);
const fingerprint = getMachineFingerprint();
const randomString = getRandomString(4);
return `c${timestampBase36}${counterBase36}${fingerprint}${randomString}`;
}
console.log(generateCUID());
Explanation
Base36 Encoding:
- The
encodeBase36
function converts a number to a Base36 encoded string.
- The
Timestamp:
const timestamp = Date.now();
gets the current timestamp in milliseconds.
Counter:
- The counter is used to handle multiple CUIDs generated within the same millisecond. The counter is incremented and reset as needed.
Machine Fingerprint:
getMachineFingerprint
generates a fingerprint using the MD5 hash of the machine's hostname.
Random String:
getRandomString
generates a random string of specified length using Base36 characters.
Combine Components:
- The
generateCUID
function combines the timestamp, counter, fingerprint, and random parts to form the final CUID.
- The
Summary
This JavaScript implementation of CUID generation uses available functions and libraries to handle timestamps, hashing, randomness, and counters. This approach ensures that the generated CUIDs are unique, readable, and collision-resistant, making them suitable for various applications.