Last active
September 24, 2021 10:08
-
-
Save amn/2ae698efc1ba2b216dc7c7b01f0c5cf7 to your computer and use it in GitHub Desktop.
A [`crypto.getRandomValues` based,] "copy avoiding" UUID-4 generator for the Web
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const uuid4 = () => { | |
const ho = (n, p) => n.toString(16).padStart(p, 0); /// Return the hexadecimal text representation of number `n`, padded with zeroes to be of length `p` | |
crypto.getRandomValues(new Uint8Array(16)); /// Fill a data buffer with random data | |
data[6] = (data[6] & 0xf) | 0x40; /// Patch the 6th byte to reflect a version 4 UUID | |
data[8] = (data[8] & 0x3f) | 0x80; /// Patch the 8th byte to reflect a variant 1 UUID (version 4 UUIDs are) | |
const view = new DataView(data.buffer); /// Create a view on the data buffer | |
return `${ho(view.getUint32(0), 8)}-${ho(view.getUint16(4), 4)}-${ho(view.getUint16(6), 4)}-${ho(view.getUint16(8), 4)}-${ho(view.getUint32(10), 8)}${ho(view.getUint16(14), 4)}`; /// Compile the canonical representation of the data | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment