DEV Community

Discussion on: How to Generate Unique ID in JavaScript

Collapse
 
roblevintennis profile image
Rob Levin

I was researching this and while I agree uuid package is probably least human error prone, it does mean potentially adding another package.

It seems like utilizing Date.now().toString or perhaps new Date().getTime() or similar and also Math.random could do the trick:

const uid = () =>
  String(
    Date.now().toString(32) +
      Math.random().toString(16)
  ).replace(/\./g, '')
Enter fullscreen mode Exit fullscreen mode

We can test it by adding generated to a map and comparing size:

const size = 1000000
const set = new Set(new Array(size)
  .fill(0)
  .map(() => uid()))

console.log(
  size === set.size ? 'all ids are unique' : `not unique records ${size - set.size}`
)
Enter fullscreen mode Exit fullscreen mode


__

Collapse
 
justingolden21 profile image
Justin Golden

This is the best comment here, and with only one like! A perfect small utility and a way to test it, all super intuitive and functional : )

Collapse
 
gregorip02 profile image
Gregori Piñeres

Your script now are in my personal helpers file. thanks.

Image description