Last active
August 18, 2021 16:58
-
-
Save nerg4l/7de56f715486fada84ac4c1f27a17b23 to your computer and use it in GitHub Desktop.
UUID draft
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
const crypto = require('crypto') | |
const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate | |
let poolPtr = rnds8Pool.length; | |
function rng(size) { | |
if (poolPtr > rnds8Pool.length - size) { | |
crypto.randomFillSync(rnds8Pool); | |
poolPtr = 0; | |
} | |
return rnds8Pool.slice(poolPtr, (poolPtr += size)); | |
} | |
const MILLISECOND_IN_NANOSECONDS = 1000 * 1000; | |
const MASK_32 = Math.pow(2, 32); | |
const storage = { | |
seq: -1, | |
lastTime: 0, | |
} | |
function uuid() { | |
const now = Date.now(); | |
if (now <= storage.lastTime) { | |
storage.seq = (storage.seq + 1) % (1024 * MILLISECOND_IN_NANOSECONDS) | |
} else { | |
storage.lastTime = now | |
storage.seq = 0 | |
} | |
let nowHigh = Math.floor(now / MASK_32) | |
let nowLow = now % MASK_32 | |
nowHigh = (nowHigh * MILLISECOND_IN_NANOSECONDS) + Math.floor((nowLow * MILLISECOND_IN_NANOSECONDS) / MASK_32) | |
nowLow = ((nowLow * MILLISECOND_IN_NANOSECONDS) % MASK_32) + Math.floor(storage.seq / Math.pow(2, 10)) | |
const arr8 = new Uint8Array(16) | |
arr8[0] = nowHigh >> 24 | |
arr8[1] = nowHigh >> 16 & 0xff | |
arr8[2] = nowHigh >> 8 & 0xff | |
arr8[3] = nowHigh & 0xff | |
arr8[4] = nowLow >> 24 | |
arr8[5] = nowLow >> 16 & 0xff | |
arr8[6] = (nowLow >> 12 & 0x0f) | 0x70 // version | |
arr8[7] = nowLow >> 4 & 0xff | |
arr8[8] = (storage.seq >> 8 & 0x03) | (nowLow & 0x3c) | 0x80 // variant | |
arr8[9] = storage.seq & 0xff | |
const rand = rng(6) | |
for (let i = 0; i < rand.length; i++) { | |
arr8[10 + i] = rand[i] | |
} | |
return { | |
toString: () => { | |
let hex = Buffer.from(arr8).toString('hex').padStart(32, '0'); | |
return hex.substring(0, 8) | |
+ '-' + hex.substring(8, 12) | |
+ '-' + hex.substring(12, 16) | |
+ '-' + hex.substring(16); | |
}, | |
get buffer() { | |
return arr8.buffer | |
}, | |
} | |
} | |
let n = 50; | |
const ids = new Array(n) | |
for (let i = 0; i < n; i++) { | |
ids[i] = uuid() | |
} | |
ids.forEach((id, i) => { | |
console.log(id.toString()) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment