Ben*_*lts 7 javascript random uuid
我目前正在使用此函数在Javascript中生成UUID(在JavaScript中创建GUID/UUID?):
lucid.uuid = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
Run Code Online (Sandbox Code Playgroud)
我知道所有随机性只来自Javascript的Math.random()函数,我不在乎它是否符合UUID的RFC.我想要的是在Javascript字符串中将尽可能多的随机性包装到尽可能少的字节中.上述函数给出了大约128位的随机性.一个字符串的小(在HTTP POST中通过线路发送的UTF8字节中测量)可以在Javascript中容纳128位吗?我将如何生成这样的字符串?
编辑:此字符串在发送到服务器时将成为JSON对象的一部分,因此需要在字符串中转义的字符不是很有用.
这是我想出的一个潜在功能。种子字符串是一组未保留的 URL 字符(共 66 个)。我在随机性前添加了大约一年的 1 秒分辨率时间戳数据,这很有用,因为我的特定应用程序的冲突空间只会随着时间的推移而相当缓慢地填充(最多每秒生成几百个)一个极端的例子)。
uuidDense = function() {
var seed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~';
//Start the UUID with 4 digits of seed from the current date/time in seconds
//(which is almost a year worth of second data).
var seconds = Math.floor((new Date().getTime())/1000);
var ret = seed[seconds % seed.length];
ret += seed[Math.floor(seconds/=seed.length) % seed.length];
ret += seed[Math.floor(seconds/=seed.length) % seed.length];
ret += seed[Math.floor(seconds/=seed.length) % seed.length];
for(var i = 0; i < 8; i++)
ret += seed[Math.random()*seed.length|0];
return ret;
}
Run Code Online (Sandbox Code Playgroud)
想法?
| 归档时间: |
|
| 查看次数: |
303 次 |
| 最近记录: |