Last active
July 4, 2023 21:00
-
-
Save emptyother/1fd97db034ef848f38eca3354fa9ee90 to your computer and use it in GitHub Desktop.
GUID class for Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Guid { | |
public static newGuid(): Guid { | |
return new Guid(crypto.randomUUID()); | |
// Old IE supported way: | |
/*return new Guid('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { | |
const r = Math.random() * 16 | 0; | |
const v = (c == 'x') ? r : (r & 0x3 | 0x8); | |
return v.toString(16); | |
}));*/ | |
} | |
public static get empty(): string { | |
return '00000000-0000-0000-0000-000000000000'; | |
} | |
public get empty(): string { | |
return Guid.empty; | |
} | |
public static isValid(str: string): boolean { | |
const validRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | |
return validRegex.test(str); | |
} | |
private value: string = this.empty; | |
constructor(value?: string) { | |
if (value) { | |
if(Guid.isValid(value)) { | |
this.value = value; | |
} | |
} | |
} | |
public toString() { | |
return this.value; | |
} | |
public toJSON(): string { | |
return this.value; | |
} | |
} | |
var e = new Guid(); | |
e; // Guid { value: '00000000-0000-0000-0000-000000000000' } | |
e.toString(); // 00000000-0000-0000-0000-000000000000 | |
console.log(e); // Guid { value: '00000000-0000-0000-0000-000000000000' } | |
JSON.stringify(e); // "00000000-0000-0000-0000-000000000000" | |
e = Guid.newGuid(); // Guid { value: 'bb90ef83-1a7e-42b1-90ba-39cdebb6366c' } | |
JSON.stringify(e); // "bb90ef83-1a7e-42b1-90ba-39cdebb6366c" | |
Guid.isValid(e.toString()); // true | |
Guid.empty; // 00000000-0000-0000-0000-000000000000 | |
Guid.isValid(Guid.empty); // false |
Thanks.its very usefull.
Nicccceeeee! Thanks!
Great
browser native alternative for V4 UUID:
crypto.randomUUID() // 'ab391b51-6732-4013-8627-27d2be558f5a'
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
Nice, thanks! Doesnt work in IE, but who cares about that anymore?
Nice, thanks! Doesnt work in IE, but who cares about that anymore?
What's IE? 😇
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, it really nice to share, can saves important time of other