Created
March 22, 2016 16:31
-
-
Save cfg/5c01568615867198c210 to your computer and use it in GitHub Desktop.
generate a v4 GUID in JS
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
| // Based on http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript | |
| var guidv4=(function(_w, lut, i){ | |
| lut = []; for (i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); } | |
| var r = Math.random, ui32=0x100000000, _crypto = _w.crypto || _w.msCrypto; | |
| return function(d) { | |
| if( _crypto && _crypto.getRandomValues ) { | |
| try { | |
| d = new Uint32Array(4); | |
| _crypto.getRandomValues(d); | |
| } catch(e) { | |
| d = 0; | |
| } | |
| } | |
| if( !d ) { | |
| d = [r()*ui32>>>0, r()*ui32>>>0, r()*ui32>>>0, r()*ui32>>>0]; | |
| } | |
| return lut[d[0]&0xff]+lut[d[0]>>8&0xff]+lut[d[0]>>16&0xff]+lut[d[0]>>24&0xff]+'-'+ | |
| lut[d[1]&0xff]+lut[d[1]>>8&0xff]+'-'+lut[d[1]>>16&0x0f|0x40]+lut[d[1]>>24&0xff]+'-'+ | |
| lut[d[2]&0x3f|0x80]+lut[d[2]>>8&0xff]+'-'+lut[d[2]>>16&0xff]+lut[d[2]>>24&0xff]+ | |
| lut[d[3]&0xff]+lut[d[3]>>8&0xff]+lut[d[3]>>16&0xff]+lut[d[3]>>24&0xff]; | |
| }; | |
| })(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment