Fork me on GitHub

Learn how to do it in JavaScript. Explore boundaries porting languages. Enjoy functions that turn out to be useful.

Here’s what a JavaScript equivalent for PHP’s uniqid looks like.

function uniqid (prefix, more_entropy) {
  //  discuss at: http://phpjs.org/functions/uniqid/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //  revised by: Kankrelune (http://www.webfaktory.info/)
  //        note: Uses an internal counter (in php_js global) to avoid collision
  //        test: skip
  //   example 1: uniqid();
  //   returns 1: 'a30285b160c14'
  //   example 2: uniqid('foo');
  //   returns 2: 'fooa30285b1cd361'
  //   example 3: uniqid('bar', true);
  //   returns 3: 'bara20285b23dfd1.31879087'

  if (typeof prefix === 'undefined') {
    prefix = ''
  }

  var retId
  var formatSeed = function (seed, reqWidth) {
    seed = parseInt(seed, 10)
      .toString(16) // to hex str
    if (reqWidth < seed.length) {
      // so long we split
      return seed.slice(seed.length - reqWidth)
    }
    if (reqWidth > seed.length) {
      // so short we pad
      return Array(1 + (reqWidth - seed.length))
        .join('0') + seed
    }
    return seed
  }

  // BEGIN REDUNDANT
  if (!this.php_js) {
    this.php_js = {}
  }
  // END REDUNDANT
  if (!this.php_js.uniqidSeed) {
    // init seed with big random int
    this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15)
  }
  this.php_js.uniqidSeed++

  // start with prefix, add current milliseconds hex string
  retId = prefix
  retId += formatSeed(parseInt(new Date()
    .getTime() / 1000, 10), 8)
  // add seed hex string
  retId += formatSeed(this.php_js.uniqidSeed, 5)
  if (more_entropy) {
    // for more entropy we add a float lower to 10
    retId += (Math.random() * 10)
      .toFixed(8)
      .toString()
  }

  return retId
}
View on GitHub Edit on GitHub Source on GitHub

A community initiative

php.js offers community built functions and goes by the McDonald’s Theory. We’ll put online functions that aren't perfect, in the hopes to spark better contributions. Do you have one? You can directly edit this file on GitHub, this will create a Pull Request that the core team can review, and merge into our codebase.

This way of working also means that we don't offer any production guarantees, and recommend to use php.js inspiration and learning purposes only.

Notes

Uses an internal counter (in php_js global) to avoid collision

Example 1

uniqid();
Should return:
'a30285b160c14'

Example 2

uniqid('foo');
Should return:
'fooa30285b1cd361'

Example 3

uniqid('bar', true);
Should return:
'bara20285b23dfd1.31879087'

« More misc functions