1.0.0 • Published 9 months ago

muid2 v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

Micro-sized unique identifiers

  • Collision-resistant
  • Timestamps encoded
  • Fast
import muid from 'muid2'

console.log(muid()) // BnKWgdls
console.log(muid()) // BnKWgds7
console.log(muid()) // BnKWgd-2
console.log(muid()) // BnKWgdEC
...
// To avoid collisions the length may be expanded under extreme loads (rarely happens)
console.log(muid()) // BnKWgdJQ7Ta
console.log(muid()) // BnKWgd_Q04W
// This resets every second though
console.log(muid()) // BnKWgeXq

// Collision resistance
const seen = new Set()
while(true){
	const id = muid()
	if(seen.has(id)){
		throw "This will never happen!"
	}
	seen.add(id)
}

import { getTimestamp, setPrefix, Muid } from 'muid2'

// Get the timestamp of a MUID, precise to the second (rounded down)
console.log(getTimestamp(muid()), Date.now()) // 1730766339000 1730766339673

// Set the prefix for concurrent ID generation
setPrefix(/*bits*/ 2, /*machine ID*/ 123n)

// E.g, for collision resistance against any other process on the system
setPrefix(24, process.pid)
// MUID is then 3 characters longer (24 bits / 6 = 3B)
console.log(muid()) // BnKWgeFb-5c

// Create standalone generators
// Generators are not collision resistant to each other
// An ID made by one may be reused by another
// Good if you don't mind reusing IDs across separate things
const gen = Muid()

console.log(gen()) // BnKWgfQr
console.log(gen()) // BnKWgfhF
console.log(gen()) // BnKWgfxS
const gen2 = Muid()
console.log(gen2() == gen()) // Might be true
console.log(gen() == gen()) // Still always false
1.0.0

9 months ago