Skip to content

Instantly share code, notes, and snippets.

@Kittoes0124
Last active December 22, 2020 16:31
Show Gist options
  • Save Kittoes0124/a6e4b4106d5515e6e1f564136654d9db to your computer and use it in GitHub Desktop.
Save Kittoes0124/a6e4b4106d5515e6e1f564136654d9db to your computer and use it in GitHub Desktop.
/*
Reference:
https://www.ietf.org/rfc/rfc4122.txt
https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
export class Guid {
private static bth: string[] = (new Array<number>(256)).fill(0).map((_, i) => i.toString(16).padStart(2, "0"));
private readonly m_value: Uint32Array;
public get value() {
return this.m_value;
}
constructor() {
const result = new Uint32Array(4);
crypto.getRandomValues(result);
result[1] = ((result[1] & 0xFFFF0FFF) | 0x00004000);
result[2] = ((result[2] & 0xFFFFFF3F) | 0x00000080);
this.m_value = result;
}
public toString(): string {
const tempValue = this.m_value;
const dataView = new DataView(tempValue.buffer, 0);
const w = dataView.getUint32(0);
const x = dataView.getUint32(4);
const y = dataView.getUint32(8);
const z = dataView.getUint32(12);
return (
Guid.bth[((w >> 24) & 0xFF)]
+ Guid.bth[((w >> 16) & 0xFF)]
+ Guid.bth[((w >> 8) & 0xFF)]
+ Guid.bth[(w & 0xFF)]
+ "-"
+ Guid.bth[((x >> 24) & 0xFF)]
+ Guid.bth[((x >> 16) & 0xFF)]
+ "-"
+ Guid.bth[((x >> 8) & 0xFF)]
+ Guid.bth[(x & 0xFF)]
+ "-"
+ Guid.bth[((y >> 24) & 0xFF)]
+ Guid.bth[((y >> 16) & 0xFF)]
+ "-"
+ Guid.bth[((y >> 8) & 0xFF)]
+ Guid.bth[(y & 0xFF)]
+ Guid.bth[((z >> 24) & 0xFF)]
+ Guid.bth[((z >> 16) & 0xFF)]
+ Guid.bth[((z >> 8) & 0xFF)]
+ Guid.bth[(z & 0xFF)]
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment