Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ID - a unique ID/name generator for JavaScript
// Do not use. Use Symbol() instead.
@thaycacac
Copy link

thaycacac commented Aug 29, 2020

thanks

@chaitanyabd
Copy link

chaitanyabd commented Sep 6, 2020

I strongly recommend using performance.now().toString(36) instead of Date.now - since it offers a higher precision date (ref: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now - you can get microsecond precision).

The advantage of a higher precision time is: the probability of users around the known universe generating their random ID in that exact same microsecond is very low.

Doing Math.random() in addition to this will result in randomization over-and-above an already extremely unique value.

function uid() {
  return (performance.now().toString(36)+Math.random().toString(36)).replace(/\./g,"");
};

Verified using @c0d3r111's Collision test
Collision test: 8391.403076171875ms
Total iterations: 1000000
Total collisions: 0
Total unique ids: 1000000

Unless your CPU can process more instructions in a microsecond, the value will likely never duplicate since you've moved into the next microsecond by the time the result comes out.

Window.crypto (ref https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto ) as @lcherone also mentioned, provides high precision random numbers, that even inspires confidence in Cryptographic algorithms (and is thus assured to be more random than other randoms), which can be used as such:

function getRandomNumbers() {
  var array = new Uint32Array(10);
  window.crypto.getRandomValues(array);
 
  for (var i = 0; i < array.length; i++) {
    console.log(array[i] + " ");
  }
}

Combining the two, here's a final function:

function uid() {
 let a = new Uint32Array(3);
 window.crypto.getRandomValues(a);
 return (performance.now().toString(36)+Array.from(a).map(A => A.toString(36)).join("")).replace(/\./g,"");
};

@NadeemAyesh
Copy link

NadeemAyesh commented Sep 28, 2020

Thank you, it was helpful :)
I have just used it in a real application.

@davemus
Copy link

davemus commented Oct 30, 2020

Thanks a lot!

@I-am-abdulazeez
Copy link

I-am-abdulazeez commented Nov 16, 2020

Awesome

@mohammadjavad948
Copy link

mohammadjavad948 commented Nov 20, 2020

Thanks!

@akshayrathodar
Copy link

akshayrathodar commented Dec 5, 2020

May Be This Will be helpful to future guys mab be this thing will never be same . Right !

function uid() {
let a = new Uint32Array(3);
window.crypto.getRandomValues(a);
return (performance.now().toString(36)+Array.from(a).map(A => A.toString(36)).join("")).replace(/./g,""+Math.random()+Intl.DateTimeFormat().resolvedOptions().timeZone+Date.now());
};

@mrap
Copy link

mrap commented Dec 16, 2020

Thanks!

@cccabdalla
Copy link

cccabdalla commented Dec 22, 2020

Very helpful. Thanks

@myebstudios
Copy link

myebstudios commented Jan 25, 2021

Thanks very much, this was very helpful for my project.

@mateusgms
Copy link

mateusgms commented Jan 29, 2021

It's so helpful! tks!

@siddiqueco
Copy link

siddiqueco commented Feb 10, 2021

I think the tittle would be "How to generate id" not unique. because there's no redundancy checking method.

@manawadkar
Copy link

manawadkar commented Mar 6, 2021

hi everyone , Good Afteroon . i need auto generate invoice number in spring boot please help

@barryspearce
Copy link

barryspearce commented Mar 22, 2021

I'm writing this in the hopes that others may find this on Google.

I had an issue that I'm using a v-for in Vue.js on a component, but in Vue 2.2+ you required :key to be set with a unique identifier. In my case the Array that it iterates over doesn't have any, so I had to generate one on demand (imagine a Bootstrap alerts manager component, e.g.). This will do just fine.

#vuejs #v-for

With vue there is an index available.
v-for="(item, idx) in blah" :key="'prefix'+idx"

By carefully choosing the prefix you can make everything on the page unique easily without additional generators.

@lcherone
Copy link

lcherone commented Mar 22, 2021

@barryspearce not sure what that's go to do with this thread 👎

@shovalPMS
Copy link

shovalPMS commented Mar 29, 2021

Helped me too! thanks

@barryspearce
Copy link

barryspearce commented Mar 30, 2021

@barryspearce not sure what that's go to do with this thread

It relates directly to the reply that I replied to. See rebers commented on 16 Jun 2017 - as quoted in my reply.
RTFQ. :)

@khryshan
Copy link

khryshan commented Apr 5, 2021

Amazing! So useful. THX!

@mhd-bakhtiari
Copy link

mhd-bakhtiari commented Apr 13, 2021

Thanks :)

@J-Zam
Copy link

J-Zam commented Apr 22, 2021

Gracias 👌

@Urento
Copy link

Urento commented Apr 25, 2021

thanks! works great

@sranjan-m
Copy link

sranjan-m commented May 22, 2021

Another way which uses a cryptographically secure random number generator, in UUID format.

var ID = () => {
  let array = new Uint32Array(8)
  window.crypto.getRandomValues(array)
  let str = ''
  for (let i = 0; i < array.length; i++) {
    str += (i < 2 || i > 5 ? '' : '-') + array[i].toString(16).slice(-4)
  }
  return str
}

This comment is the answer. It's from Mozilla Developer MDN Web Docs and supported by all kinds of browsers out there on both computer and mobile including Node.js server.
Thanks.

@scharf
Copy link

scharf commented May 31, 2021

I would go for

return ('000000000' + Math.random().toString(36).substr(2, 9)).slice(-9);

This would always return 9 digits. If the random number happens to be 0.0, the original code would return '_'.

My version would return 000000000....

@sranjan-m
Copy link

sranjan-m commented Jun 1, 2021

I would go for

return ('000000000' + Math.random().toString(36).substr(2, 9)).slice(-9);

This would always return 9 digits. If the random number happens to be 0.0, the original code would return '_'.

My version would return 000000000....

Does it pass this duplicate key test?

The following code block can also be the answer for generating a unique id. It's in the same comment towards the end after checking the duplicates

function uniqueID(){
  function chr4(){
    return Math.random().toString(16).slice(-4);
  }
  return chr4() + chr4() +
    '-' + chr4() +
    '-' + chr4() +
    '-' + chr4() +
    '-' + chr4() + chr4() + chr4();
}

uniqueID() // "e27881c4-f924-b8f7-59d9-525878c7a812"

// NOTE: This format of 8 chars, followed by 3 groups of 4 chars, followed by 12 chars
//       is known as a UUID and is defined in RFC4122 and is a standard for generating unique IDs.
//       This function DOES NOT implement this standard. It simply outputs a string
//       that looks similar. The standard is found here: https://www.ietf.org/rfc/rfc4122.txt

@samandar-boymurodov
Copy link

samandar-boymurodov commented Jun 6, 2021

thank you, I had been looking for ways to generate unique ids. finally found the better solution!

@NoTSuRe0099
Copy link

NoTSuRe0099 commented Jul 25, 2021

boi o boi thats way to great for noob like me...

Thanks...

@mohitsharma93
Copy link

mohitsharma93 commented Nov 22, 2021

what about this
return new Date().getTime().toString(36).concat(performance.now().toString(), Math.random().toString()).replace(/\./g,"");

@komiljon4717
Copy link

komiljon4717 commented Dec 2, 2021

Thanks

@swapnil-sudhir
Copy link

swapnil-sudhir commented Apr 1, 2022

Can anyone reduce the length of the string by 5-6 Characters still maintaining the collision factor ?

@was-coder
Copy link

was-coder commented Apr 4, 2022

Tha

what about this return new Date().getTime().toString(36).concat(performance.now().toString(), Math.random().toString()).replace(/\./g,"");

Thanks this was helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment