Closed jsoverson closed 12 years ago
what do you think about creating a method that returns a random hex string following any pattern?
var _chars = '0123456789abcdef'.split('');
var _defaultPattern = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx';
function guid(pattern){
var str = pattern || _defaultPattern;
str = str.replace(/x/g, function(){
return _chars[ ~~(chars.length * Math.random()) ];
});
return str;
}
so the user could do:
guid(); // "0b89907a-6344-6038-a496-5e5ca110e2"
guid('xx-xx'); // "fd-6d"
guid('#xxxxxx'); // "#b7f16c"
I usually fell that it's better to provide generic methods than very specific ones.
I was thinking about it, usually when I need to generate unique IDs I use some kind of counter to avoid generating the same value twice. I think we should probably name the method that returns a random hexadecimal value as randHex()
and default it to a 6 char string (hex color without the #
) and do it like I did above allowing a custom format for the string.
What do you think?
@jsoverson I added the randHex()
method so now it's very easy to create a guid()
method like you want:
function guid(){
return randHex(8) +'-'+ randHex(4) +'-' randHex(4) +'-'+ randHex(4) +'-'+ randHex(12);
}
or even:
function guid(){
return ('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx').replace(/x/g, function(){ return randHex(1) });
}
I don't have plans on merging the guid
method as is since it is too specific and it has a very small chance of generating the same value twice (1 in 16^32
).
Do you fell the randByte
would be useful enough to deserve it's own method? specially since it is basically a curried version of randHex(2)
?
Thanks for the pull request and feedback.
Well, the term "guid" is generally mean to refer to a formal Globally Unique Identifier which is formatted the same way everywhere. The possibility of generating identical guids in that format is considered negligible.
JavaScript can't make a genuine guid so the best it can do is a random hex (I ignored the the fixed bytes denoting a randomly generated guid but that would be a good addition).
Having a consistent format allows you to manage resources in a consistent way without having to accomodate multiple ID styles.
The random hex is fine and better. The existing implementation was just due to me being blinded working with bits and bytes for another project.
@jsoverson makes sense. do you want to refactor it or should I do it? I think we should add the "4" as first char on the 3rd group like the wikipedia article says about GUID v4.
I just pulled in your random hex and changed the spec to account for the 4
Added the ability to generate random guid strings. Added randByte to make a piece of it more reusable.
Added docs and specs using existing code as templates.
If you want to go over the code, I'm on irc in the requirejs channel generally.