Skip to content

Commit 26f57ad

Browse files
authored
Merge pull request #496 from Mozartuss/master
Add generateUUID.js
2 parents 6ef103f + f455cc3 commit 26f57ad

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

String/GenerateGUID.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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(/[xy]/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'

0 commit comments

Comments
 (0)