Files
people_manager/src/utils/key-generator.ts
2026-02-10 20:30:15 -05:00

32 lines
884 B
TypeScript

/**
* 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);
};