Skip to content

Commit 7f23418

Browse files
committed
docs(README): 'Migrating from UUID v4' section
1 parent c6b116a commit 7f23418

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ randId()
2828
- [Overkill and Under Specify](#Overkill)
2929
- [Efficiencies](#Efficiencies)
3030
- [tl;dr](#tl;dr)
31+
- [Migrating from UUID v4](#UUIDv4Migration)
3132

3233
## <a name="Overview"></a>Overview
3334

@@ -55,6 +56,63 @@ Random string generation can be thought of as a _transformation_ of some random
5556
5657
[TOC](#TOC)
5758

59+
### <a name="UUIDv4Migration"></a>Migrating from UUID v4
60+
61+
- UUID v4 has 122 bits of entropy (36 chars with hyphens; 32 hex chars without). Default `puid-js` IDs are ~132 bits in 22 URL/file-safe chars.
62+
63+
Replace uuidv4() one-off
64+
65+
```js
66+
// before
67+
import { v4 as uuidv4 } from 'uuid'
68+
const id = uuidv4()
69+
70+
// after
71+
import { generate, Chars } from 'puid-js'
72+
// ≈132 bits, 22 chars, URL/file-safe
73+
const id = generate({ chars: Chars.Safe64 })
74+
75+
// hex-like (32 chars, 128 bits)
76+
const hexId = generate({ bits: 128, chars: Chars.HexUpper })
77+
```
78+
79+
Use a generator in hot paths
80+
81+
```js
82+
import { puid, Chars } from 'puid-js'
83+
84+
// explicit bits (≈ UUID v4 or better)
85+
const { generator: id128 } = puid({ bits: 128, chars: Chars.Safe64 })
86+
87+
// or size by total/risk (10M IDs, 1e-12 repeat risk)
88+
const { generator: sized } = puid({ total: 1e7, risk: 1e12, chars: Chars.Safe64 })
89+
90+
const id = id128()
91+
```
92+
93+
Browser
94+
95+
```js
96+
import { generate, Chars } from 'puid-js/web'
97+
const id = generate({ chars: Chars.Safe64 })
98+
```
99+
100+
Error handling for generate()
101+
102+
```js
103+
try {
104+
generate({ total: 1000 }) // invalid: missing risk
105+
} catch (err) {
106+
// handle invalid config
107+
}
108+
```
109+
110+
Notes
111+
- If your DB/validators assume UUID format/length, update to accept generic ID strings. Default Safe64 is 22 chars; HexUpper at 128 bits is 32 chars.
112+
- Charset guidance: Safe64 (shortest URL/file-safe), Hex/HexUpper (compat), Safe32/WordSafe32 (human-friendlier).
113+
114+
And remember, you rarely need the 122-bytes of entropy provided by UUID, and you certainly never need the inefficiency of the string representation!
115+
58116
### <a name="Usage"></a>Usage
59117

60118
Creating a random ID generator using `puid-js` is as simple as:

0 commit comments

Comments
 (0)