PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/functions/misc/uniqid.js

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