-
-
Save SimonHoiberg/ad2710c8626c5a74cddd8f6385795cc0 to your computer and use it in GitHub Desktop.
Create a unique string
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 uid = () => { | |
return Date.now().toString(36) + Math.random().toString(36).substr(2); | |
}; | |
// Usage. Example, id = khhry2hb7uip12rj2iu | |
const id = uid(); |
I'm still not sure if I like or dislike that the IDs' alphabetical sort order is also the order by creation time...
You guys sure know about this one? https://gist.github.com/jed/982883
You guys sure know about this one? https://gist.github.com/jed/982883
Sure, but this here is still nice for smaller use cases and 87% faster on my machine: https://jsbench.me/ovkhvq1uct/1
how about using
performance.now()
instead ofDate.now()
? It should reduce the probability of collision further.
It will only work on the web, not under Nodejs
Seriously...
https://www.npmjs.com/package/uuid
import { v4 as uuidv4 } from 'uuid';
const myKey = uuidv4();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Absolutely. This is well-known.
That's why it is combined with
Date.now()
.Let me also just state that this is great for smaller lists and for quickly generating temporary unique strings.
It shouldn't be used for more serious cases, where collisions should be taken into account.
In those cases, use uuid4 instead.