-
-
Save yanqiw/5071064 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 还需要了解的: | |
// - 什么是 UID | |
// - 这四种方式优劣 | |
function getId() { | |
return "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/x/g, function() { | |
return Math.floor(Math.random()*16).toString(16).toUpperCase(); | |
}); | |
} | |
function generateGuid() { | |
var result, i, j; | |
result = ''; | |
for(j=0; j<32; j++) { | |
if( j == 8 || j == 12|| j == 16|| j == 20) | |
result = result + '-'; | |
i = Math.floor(Math.random()*16).toString(16).toUpperCase(); | |
result = result + i; | |
} | |
return result; | |
} | |
// http://stackoverflow.com/questions/3242324/javascript-dateobj-gettime-for-a-uid-is-the-length-not-fixed | |
Math.random().toString(36).substr(2,9) | |
// http://stackoverflow.com/questions/6248666/how-to-generate-short-uid-like-ax4j9z-in-js | |
function generateUIDNotMoreThan1million() { | |
return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).substr(-4) | |
} | |
//================ | |
function generateUUID(){ | |
var d = new Date().getTime(); | |
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { | |
var r = (d + Math.random()*16)%16 | 0; | |
d = Math.floor(d/16); | |
return (c=='x' ? r : (r&0x7|0x8)).toString(16); | |
}); | |
return uuid; | |
}; | |
//================= | |
generateGUID = (typeof(window.crypto) != 'undefined' && | |
typeof(window.crypto.getRandomValues) != 'undefined') ? | |
function() { | |
// If we have a cryptographically secure PRNG, use that | |
// http://stackoverflow.com/questions/6906916/collisions-when-generating-uuids-in-javascript | |
var buf = new Uint16Array(8); | |
window.crypto.getRandomValues(buf); | |
var S4 = function(num) { | |
var ret = num.toString(16); | |
while(ret.length < 4){ | |
ret = "0"+ret; | |
} | |
return ret; | |
}; | |
return (S4(buf[0])+S4(buf[1])+"-"+S4(buf[2])+"-"+S4(buf[3])+"-"+S4(buf[4])+"-"+S4(buf[5])+S4(buf[6])+S4(buf[7])); | |
} | |
: | |
function() { | |
// Otherwise, just use Math.random | |
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 | |
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); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment