UNPKG

678 BJavaScriptView Raw
1import rng from './rng.js';
2import bytesToUuid from './bytesToUuid.js';
3
4function v4(options, buf, offset) {
5 if (typeof options === 'string') {
6 buf = options === 'binary' ? new Uint8Array(16) : null;
7 options = null;
8 }
9
10 options = options || {};
11 const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
12
13 rnds[6] = rnds[6] & 0x0f | 0x40;
14 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
15
16 if (buf) {
17 const start = offset || 0;
18
19 for (let i = 0; i < 16; ++i) {
20 buf[start + i] = rnds[i];
21 }
22
23 return buf;
24 }
25
26 return bytesToUuid(rnds);
27}
28
29export default v4;
\No newline at end of file