File tree Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Generates a UUID/GUID in Node.Js.
3+ The script uses `Math.random` in combination with the timestamp for better randomness.
4+ The function generate an RFC4122 (https://www.ietf.org/rfc/rfc4122.txt) version 4 UUID/GUID
5+ */
6+
7+ const Guid = ( ) => {
8+ const pattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
9+ let currentDateMilliseconds = new Date ( ) . getTime ( )
10+ return pattern . replace ( / [ x y ] / g, currentChar => {
11+ const randomChar = ( currentDateMilliseconds + Math . random ( ) * 16 ) % 16 | 0
12+ currentDateMilliseconds = Math . floor ( currentDateMilliseconds / 16 )
13+ return ( currentChar === 'x' ? randomChar : ( randomChar & 0x7 | 0x8 ) ) . toString ( 16 )
14+ } )
15+ }
16+
17+ console . log ( Guid ( ) ) // 'edc848db-3478-1760-8b55-7986003d895f'
You can’t perform that action at this time.
0 commit comments