Skip to content

Commit b651e54

Browse files
committed
add generateUUID.js
1 parent 6c47ed9 commit b651e54

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

String/generateUUID.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* Generates a UUID/GUID in Node.Js or browser.
2+
3+
In the browser the script uses the `window.crypto` or `window.msCrypto` (IE11) API
4+
On server-side the script uses `Math.random` in combination with the timestamp for better randomness.
5+
The function generate an RFC4122 (https://www.ietf.org/rfc/rfc4122.txt) version 4 UUID/GUID
6+
7+
*/
8+
const Guid = () => {
9+
const crypto = typeof window || window.crypto || window.msCrypto || null
10+
const pattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
11+
12+
const _padLeft = (paddingString, width, replacementChar) =>
13+
paddingString.length >= width
14+
? paddingString
15+
: _padLeft(replacementChar + paddingString, width, replacementChar || ' ')
16+
17+
const _quart = number => {
18+
const hexadecimalResult = number.toString(16)
19+
return _padLeft(hexadecimalResult, 4, '0')
20+
}
21+
const _cryptoGuid = () => {
22+
const buffer = new window.Uint16Array(8)
23+
window.crypto.getRandomValues(buffer)
24+
return [_quart(buffer[0]) +
25+
_quart(buffer[1]), _quart(buffer[2]), _quart(buffer[3]), _quart(buffer[4]), _quart(buffer[5]) +
26+
_quart(buffer[6]) +
27+
_quart(buffer[7])].join('-')
28+
}
29+
const _guid = () => {
30+
let currentDateMilliseconds = new Date().getTime()
31+
return pattern.replace(/[xy]/g, currentChar => {
32+
const randomChar = (currentDateMilliseconds + Math.random() * 16) % 16 | 0
33+
currentDateMilliseconds = Math.floor(currentDateMilliseconds / 16)
34+
return (currentChar === 'x' ? randomChar : (randomChar & 0x7 | 0x8)).toString(16)
35+
})
36+
}
37+
38+
return crypto !== 'undefined' && crypto !== null
39+
? typeof (window.crypto.getRandomValues) !== 'undefined'
40+
? _cryptoGuid()
41+
: _guid()
42+
: _guid()
43+
}
44+
45+
console.log(Guid()) // 'edc848db-3478-1760-8b55-7986003d895f'

0 commit comments

Comments
 (0)