-
Notifications
You must be signed in to change notification settings - Fork 0
/
Guid.ts
59 lines (53 loc) · 1.23 KB
/
Guid.ts
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
/**
* Global unique identifiers, RFC4122 v4 compatible.
*/
export class Guid {
/**
* Internal string representation of the GUID.
*/
private guid: string;
/**
* Create a new Guid.
* @param g A GUID formatted string.
*/
constructor (g: string) {
this.guid = g;
}
/**
* Returns the GUID formatted as a string.
*/
public toString(): string {
return this.guid;
}
/**
* Returns the GUID formatted for JSON
*/
public toJSON(): Object {
return this.guid;
}
/**
* Creates a new Guid from a string.
* If it is a valid RFC4122 v4 GUID, it returns the Guid object, null otherwise.
*/
public static parse(guid: string): Guid {
let pattern = /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/;
if (pattern.test(guid)) {
return new Guid(guid);
}
return null;
}
/**
* Creates a new GUID class.
* Conforms to RFC4122 v4.
* @return string Formatted RFC4122 v4 GUID.
*/
public static newGuid(): Guid {
let d = new Date().getTime();
let uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r&0x3|0x8)).toString(16);
});
return new Guid(uuid);
}
}