Last active
January 18, 2023 13:40
-
-
Save benjaminudoh10/b0860ac0e6ea3208f380012d072fa68d to your computer and use it in GitHub Desktop.
Naive implementation of version 4 uuid generator
This file contains 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
import * as crypto from 'crypto'; | |
function v4_uuid() { | |
let rand_bytes = crypto.randomBytes(16); | |
let rand_bytes_int = Uint8Array.from(rand_bytes); | |
// replace 7th byte with 4 (0100) | |
// & 0b00001111 replaces the first 4 bits with 0s | |
// | 0b01000000 replaces the first 4 bits with 0100 | |
rand_bytes_int[6] = (rand_bytes_int[6] & 0b00001111) | 0b01000000; | |
// set 2 significant bits of 9th byte to 2 (10) | |
// & 0b00111111 replaces the first 2 bits with 0s | |
// | 0b10000000 replaces the first 2 bits with 10 | |
rand_bytes_int[8] = (rand_bytes_int[8] & 0b00111111) | 0b10000000; | |
let output = ''; | |
const hyphen_points = [2, 4, 6, 8]; | |
for (let i = 0; i < rand_bytes_int.length; i++) { | |
output += rand_bytes_int[i].toString(16).padStart(2, '0'); | |
if (hyphen_points.includes(i)) { | |
output += '-'; | |
} | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment