Created
May 23, 2013 19:57
-
-
Save ain/5638966 to your computer and use it in GitHub Desktop.
JavaScript alternative of PHP uniqid()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function uniqid (prefix, more_entropy) { | |
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) | |
// + revised by: Kankrelune (http://www.webfaktory.info/) | |
// % note 1: Uses an internal counter (in php_js global) to avoid collision | |
// * 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++; | |
retId = prefix; // start with prefix, add current milliseconds hex string | |
retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8); | |
retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string | |
if (more_entropy) { | |
// for more entropy we add a float lower to 10 | |
retId += (Math.random() * 10).toFixed(8).toString(); | |
} | |
return retId; | |
} |
According to this comment on stack overflow, https://stackoverflow.com/a/2472969/27759437, this seems closer to the PHP implementation:
In PHP
$m = microtime(true);
$uniqid = sprintf("%8x%05x", floor($m), ($m - floor($m)) * 1000000);
In TypeScript:
const uniqid = (prefix: string = '', moreEntropy: boolean = false) => {
const precisionTime = performance.timeOrigin + performance.now();
const seconds = Math.floor(precisionTime / 1000);
const part1 = seconds.toString(16).substring(0, 8);
const microseconds = (precisionTime - seconds * 1000) * 1000;
const part2 = Math.floor(microseconds)
.toString(16)
.substring(0, 5)
.padStart(5, '0');
return (
prefix +
part1 +
part2 +
(moreEntropy ? (Math.random() * 10).toFixed(8).toString() : '')
);
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you bro ;-)