-
Notifications
You must be signed in to change notification settings - Fork 1
/
uuid.js
76 lines (60 loc) · 1.41 KB
/
uuid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
var rng = require('./rng');
var isBuffer = require('is-buffer');
var isArray = Array.isArray;
var reduce = Array.prototype.reduce;
var toArray = Array.prototype.slice;
module.exports = {
v4: v4,
parse: parse,
unparse: unparse
};
function v4 (opts) {
var bytes = rng();
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
return (opts && opts.bytes)
? toArray.call(bytes)
: unparse(bytes);
}
function parse (str) {
if (typeof str !== 'string') {
throw new TypeError('expecting a String');
}
var bytes = str
.toLowerCase()
.match(/[0-9a-f]{2}/g)
.map(toByte);
if (bytes.length !== 16) {
throw new Error('malformed UUID');
}
return bytes;
}
function unparse (bytes) {
if (!isArray(bytes) && !isUint8Array(bytes) && !isBuffer(bytes)) {
throw new TypeError('expecting Array, Uint8Array or Buffer');
}
if (bytes.length !== 16) {
throw new Error('expecting length of 16');
}
return reduce.call(bytes, unparseReducer, '');
}
function unparseReducer (str, bytes, i) {
return str + dashOrNothing(i) + toHex(bytes);
}
function dashOrNothing (i) {
return (i === 4 || i === 6 || i === 8 || i === 10)
? '-'
: '';
}
function toByte (hex) {
return parseInt(hex, 16);
}
function toHex (byte) {
return (byte + 0x100)
.toString(16)
.substr(1);
}
function isUint8Array (bytes) {
return bytes instanceof Uint8Array;
}