Skip to content

Instantly share code, notes, and snippets.

@kevinbull
Forked from jed/LICENSE.txt
Last active April 12, 2022 12:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kevinbull/f1cbc5440aa713bd5c9e to your computer and use it in GitHub Desktop.
Save kevinbull/f1cbc5440aa713bd5c9e to your computer and use it in GitHub Desktop.
Using JavaScript generate a 32 character hexadecimal universal id string.

generateUnid

Each call returns a random 32 character hexidecimal string. Based on the work done https://gist.github.com/jed/982883

Usage:

<script src="https://gist.github.com/kevinbull/f1cbc5440aa713bd5c9e.js"></script>

var unid = generateUnid();
console.log(unid);

This was tested and created 300k unids in about 1 second with no duplicates on a 2018 MacBook Pro.

A stress test for creating a million unids is included in the code pen. Each time it was tested it never created duplicate unids.

Example: https://codepen.io/kbullman/pen/KKpjVJG?editors=1111

function uniqueArray(a) {
  //for a case insensitive version if array values are strings
  //return Array.from(new Set(a.map(v => v.toLowerCase())));
  // This is case sensitive
  return Array.from(new Set(a));
}

function generateUnids() {
  let unids = []
  let start = performance.now()
  for (let i = 0 ; i < 1000000 ; i++) {
    unids.push(generateUnid())
  }
  let elapsed = Number(performance.now() - start).toLocaleString()
  let uniqueItems = uniqueArray(unids)
  //let test = uniqueArray(['kevin', 'pepsi', 'Kevin', 'pepsi', 'Coke'])
  
  let msg = [
    `Elasped time ${elapsed} milliseconds`,
    `There were ${Number(unids.length - uniqueItems.length).toLocaleString()} duplicates out of ${unids.length.toLocaleString()} generated unids.`
    ]
  
  // The codepen has this element so it can be used in that context
  //document.getElementById("value").innerHTML = msg.join('<br />');
  console.log(msg)
}
function generateUnid(
a // placeholder
){
return a // if the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
Math.random() // in which case
* 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e10] +
1e10 +
1e9
).replace( // replacing
/[01]/g, // zeroes and ones with
generateUnid // random hex digits
).toUpperCase()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment