Last active
February 15, 2017 11:57
-
-
Save wilcorrea/3b39d158daa0da8e5c59bdfd90a4c61e 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 | |
DROP FUNCTION IF EXISTS hashKey; | |
CREATE FUNCTION `hashKey`() | |
RETURNS VARCHAR(13) | |
BEGIN | |
RETURN CONCAT( | |
LOWER(SUBSTR(HEX(UNIX_TIMESTAMP(NOW(5)) / 1), 1, 8)), | |
LOWER(SUBSTR(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