Created
July 5, 2021 01:27
-
-
Save Aaron-P/3ddbe9aa7d85807d94e19a6000dd1f58 to your computer and use it in GitHub Desktop.
JavaScript UUID v4 generation
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
| function UUIDv4() { | |
| const bytes = new Uint8Array(16); | |
| window.crypto.getRandomValues(bytes); | |
| bytes[6] = (bytes[6] & 0x0f) | 0x40; | |
| bytes[8] = (bytes[8] & 0x3f) | 0x80; | |
| // Is there a better way of getting our string from the byte array? | |
| const hex = bytes.reduce((output, byte) => (output + ("0" + byte.toString(16)).slice(-2)), ""); | |
| return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20, 32)}`; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment