ID - a unique ID/name generator for JavaScript (github.com)
ID - a unique ID/name generator for JavaScript
ID - a unique ID/name generator for JavaScript. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
I strongly recommend using performance.now().toString(36) instead of Date.now - since it offers a higher precision date (ref: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now - you can get microsecond precision).
The advantage of a higher precision time is: the probability of users around the known universe generating their random ID in that exact same microsecond is very low.
Doing Math.random() in addition to this will result in randomization over-and-above an already extremely unique value.
function uid() {
return (performance.now().toString(36)+Math.random().toString(36)).replace(/\./g,"");
};
Verified using @c0d3r111's Collision test
Collision test: 8391.403076171875ms
Total iterations: 1000000
Total collisions: 0
Total unique ids: 1000000
Unless your CPU can process more instructions in a microsecond, the value will likely never duplicate since you've moved into the next microsecond by the time the result comes out.
Window.crypto (ref https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto ) as @lcherone also mentioned, provides high precision random numbers, that even inspires confidence in Cryptographic algorithms (and is thus assured to be more random than other randoms), which can be used as such:
function getRandomNumbers() {
var array = new Uint32Array(10);
window.crypto.getRandomValues(array);
for (var i = 0; i < array.length; i++) {
console.log(array[i] + " ");
}
}
Combining the two, here's a final function:
function uid() {
let a = new Uint32Array(3);
window.crypto.getRandomValues(a);
return (performance.now().toString(36)+Array.from(a).map(A => A.toString(36)).join("")).replace(/\./g,"");
};
'Javascript > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฐ์คํฌ๋ฆฝํธ] ์ ๋๋ ์ดํฐ (0) | 2022.04.19 |
---|---|
[์๋ฐ์คํฌ๋ฆฝํธ] how to remove array element javascript (0) | 2022.04.17 |
์๋ฐ์คํฌ๋ฆฝํธ ๋ฐ๋ณต๋ฌธ (0) | 2022.04.14 |
[๋๋ฆผ์ฝ๋ฉ ์๋ฐ์คํฌ๋ฆฝํธ] ๋น๋๊ธฐ promise (0) | 2022.04.13 |
[๋๋ฆผ์ฝ๋ฉ ์๋ฐ์คํฌ๋ฆฝํธ]๋น๋๊ธฐ์ ์์ ์ฝ๋ฐฑ์ง์ฅ (0) | 2022.04.13 |