@datadayrepos/js-id-web
Version:
Utils for generating identifiers in javascript browser environment. Using web crypto engine for random number generation.
17 lines (16 loc) • 717 B
JavaScript
import { randInt1 } from '../crypto/index.js';
export function UUIDPolyfill() {
const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const randomChar1 = alphabet[randInt1() % alphabet.length];
const randomChar2 = alphabet[randInt1() % alphabet.length];
let dt = new Date().getTime() + randomChar1.charCodeAt(0) + randomChar2.charCodeAt(0);
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (dt + randInt1() % 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return { error: null, result: uuid };
}
export function UUID() {
return crypto.randomUUID();
}