mercredi 5 octobre 2016

Generating unique base-64 ID's in javascript

I'm making an application in which I need to generate Unique IDs.

When generating IDs the best way to avoid clashes, is it simply brute force generate-then-check'ing, or is there a way to garuantee unique generation.

I'm sure the brute force method would do well for a while however I have a feeling companies like Google aren't using this method.

The other things is how to actually generate them in node.js.

I thought of generating int's from '0 - 63' and then parsing to base-64 like this:

var map = {
    0:0, 1:1 ... 16:"Q" ... 63:"/"
}; /* I used object so you can see the indexes, 
this would be an array - or even a string? */
for (var i = IDLENGTH, id=""; i--;) id+=map[~~(Math.random*64)];

However this seems inneficient, especially having the map in the first place.

I saw this peice of code in another SO post

console.log(new Buffer("Hello World").toString('base64'));
> SGVsbG8gV29ybGQ=

Which seems to make more sense, but this doesn't seem to fit what I need, isn't this conversion of char-sets?




Aucun commentaire:

Enregistrer un commentaire