2

I want to generate unique ids for some variables. I need to create a new id everytime for some variable.

Is it safe to use such kind of code?

var id = 'id_' + (new Date()).getTime();

I need to make sure there's no duplicate id during running my script.

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119
  • Perhaps [this question](https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid) is better suited for your needs – dubes Jun 21 '21 at 10:26
  • your ID will only be unqique if two instances of your script are not running at the same millisecond, low chances but not impossible – empiric Jun 21 '21 at 10:27
  • 2
    try it yourself `(new Date()).getTime() === (new Date()).getTime()` ... oops, it's true – Jaromanda X Jun 21 '21 at 10:28
  • Why do you need these IDs? There are most likely better ways, e.g. if you want to distinguish multiple objects, use a [`Map`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). – Sebastian Simon Jun 21 '21 at 10:32
  • `(new Date()).getTime()` the same as `Date.now()`. you can create a function that return new "id" `const getUniqId = () => Date.now()` – Omer Jun 21 '21 at 10:38

2 Answers2

3

I don't think that's ideal for generating unique ids, I'd suggest using UUIDs instead. They are globally unique, you will never get collisions.

If you make several calls of 'id_' + (new Date()).getTime() in the same millisecond, you will get duplicated ids.

You can easily create UUIDs using the uuid library:

   
const ids = Array.from({ length: 5}, () => uuid.v4());
console.log("Ids:", ids);
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js" integrity="sha512-UNM1njAgOFUa74Z0bADwAq8gbTcqZC8Ej4xPSzpnh0l6KMevwvkBvbldF9uR++qKeJ+MOZHRjV1HZjoRvjDfNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

You'll see that if you generate a bunch of ids at the same time they can easily be duplicates, so that approach will be very risky:

let ids = Array.from({ length: 5}, () => 'id_' + (new Date()).getTime());

console.log("IDS:", ids);
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
1

UUID package is recommended of course but perhaps you can still get pretty unique IDs by doing

(Date.now()*Math.random()).toString(36).replace(".","").toUpperCase()

Lets test a 1000000 successively generated IDs for uniqueness.

var uid      = _ => (Date.now()*Math.random()).toString(36).replace(".","").toUpperCase(),
    uids     = Array.from({length:1000000}, _ => uid())
                    .sort(),
    isUnique = uids.slice(1)
                   .every((id,ix) => id !== uids[ix]);

console.log(isUnique);
Redu
  • 25,060
  • 6
  • 56
  • 76