Initial commit
This commit is contained in:
31
src/utils/key-generator.ts
Normal file
31
src/utils/key-generator.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Utility functions for generating unique identifiers
|
||||
*/
|
||||
|
||||
const globalCrypto = typeof globalThis !== "undefined" ? globalThis.crypto : undefined;
|
||||
|
||||
export const generateUrid = (): string => {
|
||||
if (globalCrypto?.randomUUID) {
|
||||
return globalCrypto.randomUUID();
|
||||
}
|
||||
|
||||
const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
|
||||
return template.replace(/[xy]/g, char => {
|
||||
const randomNibble = Math.floor(Math.random() * 16);
|
||||
const value = char === "x" ? randomNibble : (randomNibble & 0x3) | 0x8;
|
||||
return value.toString(16);
|
||||
});
|
||||
};
|
||||
|
||||
export const generateKey = (): string => {
|
||||
if (globalCrypto?.randomUUID) {
|
||||
return globalCrypto.randomUUID().replace(/-/g, "");
|
||||
}
|
||||
|
||||
if (globalCrypto?.getRandomValues) {
|
||||
const [value] = globalCrypto.getRandomValues(new Uint32Array(1));
|
||||
return value.toString(16);
|
||||
}
|
||||
|
||||
return Math.random().toString(16).slice(2);
|
||||
};
|
||||
Reference in New Issue
Block a user