|
1 | 1 | /** |
2 | | - * Source: [jed's gist]{@link https://gist.github.com/982883}. |
| 2 | + * Source: [jed's gist's comment]{@link https://gist.github.com/jed/982883?permalink_comment_id=3223002#gistcomment-3223002}. |
3 | 3 | * Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, |
4 | 4 | * where each x is replaced with a random hexadecimal digit from 0 to f, and |
5 | 5 | * y is replaced with a random hexadecimal digit from 8 to b. |
6 | 6 | * Used to generate UUIDs for deviceIds. |
7 | 7 | * @private |
8 | 8 | */ |
9 | | -var uuid = function (a) { |
10 | | - return a // if the placeholder was passed, return |
11 | | - ? // a random number from 0 to 15 |
12 | | - ( |
13 | | - a ^ // unless b is 8, |
14 | | - ((Math.random() * // in which case |
15 | | - 16) >> // a random number from |
16 | | - (a / 4)) |
17 | | - ) // 8 to 11 |
18 | | - .toString(16) // in hexadecimal |
19 | | - : // or otherwise a concatenated string: |
20 | | - ( |
21 | | - [1e7] + // 10000000 + |
22 | | - -1e3 + // -1000 + |
23 | | - -4e3 + // -4000 + |
24 | | - -8e3 + // -80000000 + |
25 | | - -1e11 |
26 | | - ) // -100000000000, |
27 | | - .replace( |
28 | | - // replacing |
29 | | - /[018]/g, // zeroes, ones, and eights with |
30 | | - uuid, // random hex digits |
31 | | - ); |
| 9 | + |
| 10 | +// hoist hex table out of the function to avoid re-calculation |
| 11 | +const hex = [...Array(256).keys()].map((index) => index.toString(16).padStart(2, '0')); |
| 12 | + |
| 13 | +var uuid = () => { |
| 14 | + const r = crypto.getRandomValues(new Uint8Array(16)); |
| 15 | + |
| 16 | + r[6] = (r[6] & 0x0f) | 0x40; |
| 17 | + r[8] = (r[8] & 0x3f) | 0x80; |
| 18 | + |
| 19 | + return [...r.entries()].map(([index, int]) => ([4, 6, 8, 10].includes(index) ? `-${hex[int]}` : hex[int])).join(''); |
32 | 20 | }; |
33 | 21 |
|
34 | 22 | export default uuid; |
0 commit comments