PageRenderTime 55ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/functions/misc/uniqid.js

http://github.com/kvz/phpjs
JavaScript | 46 lines | 30 code | 4 blank | 12 comment | 7 complexity | cff2d29f55931ed78ce1ee6ab08ee5cf MD5 | raw file
  1. function uniqid (prefix, more_entropy) {
  2. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  3. // + revised by: Kankrelune (http://www.webfaktory.info/)
  4. // % note 1: Uses an internal counter (in php_js global) to avoid collision
  5. // * example 1: uniqid();
  6. // * returns 1: 'a30285b160c14'
  7. // * example 2: uniqid('foo');
  8. // * returns 2: 'fooa30285b1cd361'
  9. // * example 3: uniqid('bar', true);
  10. // * returns 3: 'bara20285b23dfd1.31879087'
  11. if (typeof prefix == 'undefined') {
  12. prefix = "";
  13. }
  14. var retId;
  15. var formatSeed = function (seed, reqWidth) {
  16. seed = parseInt(seed, 10).toString(16); // to hex str
  17. if (reqWidth < seed.length) { // so long we split
  18. return seed.slice(seed.length - reqWidth);
  19. }
  20. if (reqWidth > seed.length) { // so short we pad
  21. return Array(1 + (reqWidth - seed.length)).join('0') + seed;
  22. }
  23. return seed;
  24. };
  25. // BEGIN REDUNDANT
  26. if (!this.php_js) {
  27. this.php_js = {};
  28. }
  29. // END REDUNDANT
  30. if (!this.php_js.uniqidSeed) { // init seed with big random int
  31. this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
  32. }
  33. this.php_js.uniqidSeed++;
  34. retId = prefix; // start with prefix, add current milliseconds hex string
  35. retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
  36. retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string
  37. if (more_entropy) {
  38. // for more entropy we add a float lower to 10
  39. retId += (Math.random() * 10).toFixed(8).toString();
  40. }
  41. return retId;
  42. }