-
-
Save IgorDePaula/8fb382425b9b3574bb89b0377df6037c to your computer and use it in GitHub Desktop.
Função do PHP uniqid em SQL e JS
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
// http://locutus.io/php/misc/uniqid/ | |
function uniqid (prefix, moreEntropy) => { | |
if (typeof prefix === 'undefined') { | |
prefix = ''; | |
} | |
let retId; | |
const _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 new Array(1 + (reqWidth - seed.length)).join('0') + seed | |
} | |
return seed; | |
}; | |
let $global = (typeof window !== 'undefined' ? window : global); | |
$global.$locutus = $global.$locutus || {}; | |
let $locutus = $global.$locutus; | |
$locutus.php = $locutus.php || {}; | |
if (!$locutus.php.uniqidSeed) { | |
// init seed with big random int | |
$locutus.php.uniqidSeed = Math.floor(Math.random() * 0x75bcd15); | |
} | |
$locutus.php.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($locutus.php.uniqidSeed, 5); | |
if (moreEntropy) { | |
// for more entropy we add a float lower to 10 | |
retId += (Math.random() * 10).toFixed(8).toString(); | |
} | |
return retId | |
} |
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
# TODO: add prefix and moreEntropy | |
CREATE FUNCTION `uniqid`() | |
RETURNS VARCHAR(13) | |
BEGIN | |
RETURN concat( | |
lower(substring(hex(floor(UNIX_TIMESTAMP(NOW(2))*1000)), 1, 8)), | |
lower(substring(hex((floor(rand() * 0x75bcd15))), 1, 5)) | |
); | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment