Created
February 24, 2019 17:44
-
-
Save mukoladeath/e208c079bab582990ff5ab17dc0a2bce to your computer and use it in GitHub Desktop.
Uniqid function, based on pure javascript Time and Random
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
//uniqId('_') | |
//"_jsj7byjvm1f6df87o" | |
//uniqId('.') | |
//".jsj7c2bbo0nydbmwi" | |
//uniqId('prefix_') | |
//"prefix_jsj7cdqe37ecl3eig" | |
function uniqId(separator){ | |
var separator = separator || ''; | |
return separator+(new Date().getTime()).toString(36)+Math.random().toString(36).substr(2, 9); | |
} | |
//version 2 | |
//* `uniqId2()` - returns `52643b81917b3` | |
//* `uniqId2('prefix_')` - returns `prefix_52643bb682821` | |
//* `uniqId2('prefix_', true)` - returns `prefix_52643bdf3b1fb7.38568327` | |
function uniqId2(pr, en) { | |
var pr = pr || '', en = en || false, result, us; | |
this.seed = function (s, w) { | |
s = parseInt(s, 10).toString(16); | |
return w < s.length ? s.slice(s.length - w) : | |
(w > s.length) ? new Array(1 + (w - s.length)).join('0') + s : s; | |
}; | |
result = pr + this.seed(parseInt(new Date().getTime() / 1000, 10), 8) | |
+ this.seed(Math.floor(Math.random() * 0x75bcd15) + 1, 5); | |
if (en) result += (Math.random() * 10).toFixed(8).toString(); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment