generateRandomUuid.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. define("dojox/uuid/generateRandomUuid", ['./_base'], function(){
  2. dojox.uuid.generateRandomUuid = function(){
  3. // summary:
  4. // This function generates random UUIDs, meaning "version 4" UUIDs.
  5. // description:
  6. // A typical generated value would be something like this:
  7. // "3b12f1df-5232-4804-897e-917bf397618a"
  8. //
  9. // For more information about random UUIDs, see sections 4.4 and
  10. // 4.5 of RFC 4122: http://tools.ietf.org/html/rfc4122#section-4.4
  11. //
  12. // This generator function is designed to be small and fast,
  13. // but not necessarily good.
  14. //
  15. // Small: This generator has a small footprint. Once comments are
  16. // stripped, it's only about 25 lines of code, and it doesn't
  17. // dojo.require() any other modules.
  18. //
  19. // Fast: This generator can generate lots of new UUIDs fairly quickly
  20. // (at least, more quickly than the other dojo UUID generators).
  21. //
  22. // Not necessarily good: We use Math.random() as our source
  23. // of randomness, which may or may not provide much randomness.
  24. // examples:
  25. // var string = dojox.uuid.generateRandomUuid();
  26. var HEX_RADIX = 16;
  27. function _generateRandomEightCharacterHexString(){
  28. // Make random32bitNumber be a randomly generated floating point number
  29. // between 0 and (4,294,967,296 - 1), inclusive.
  30. var random32bitNumber = Math.floor( (Math.random() % 1) * Math.pow(2, 32) );
  31. var eightCharacterHexString = random32bitNumber.toString(HEX_RADIX);
  32. while(eightCharacterHexString.length < 8){
  33. eightCharacterHexString = "0" + eightCharacterHexString;
  34. }
  35. return eightCharacterHexString; // for example: "3B12F1DF"
  36. }
  37. var hyphen = "-";
  38. var versionCodeForRandomlyGeneratedUuids = "4"; // 8 == binary2hex("0100")
  39. var variantCodeForDCEUuids = "8"; // 8 == binary2hex("1000")
  40. var a = _generateRandomEightCharacterHexString();
  41. var b = _generateRandomEightCharacterHexString();
  42. b = b.substring(0, 4) + hyphen + versionCodeForRandomlyGeneratedUuids + b.substring(5, 8);
  43. var c = _generateRandomEightCharacterHexString();
  44. c = variantCodeForDCEUuids + c.substring(1, 4) + hyphen + c.substring(4, 8);
  45. var d = _generateRandomEightCharacterHexString();
  46. var returnValue = a + hyphen + b + hyphen + c + d;
  47. returnValue = returnValue.toLowerCase();
  48. return returnValue; // String
  49. };
  50. return dojox.uuid.generateRandomUuid;
  51. });