crypto.randomUUIDのPolyfill実装
全ブラウザでサポートされているので今さら実装する理由はない。
TypeScript
Section titled “TypeScript”type UUID = `${string}-${string}-${string}-${string}-${string}`;
const FN_NAME = "randomUUID";const BASE_STR = [1e7, 1e3, 4e3, 8e3, 1e11].join("-");
const api = crypto;
/*** UUIDを生成します* ブラウザがrandomUUIDをサポートしていない場合はポリフィル実装を実行する* @returns {UUID}*/export function randomUUID(): UUID { const api = crypto; if (FN_NAME in api) return api[FN_NAME]();
return BASE_STR.replace(/[018]/g, replacer) as UUID;}
function replacer(char: string): string { const random = api.getRandomValues(new Uint8Array(1))[0]; const int = Number.parseInt(char); return (int ^ (random & (15 >> (int / 4))).toString(16);}
JavaScript
Section titled “JavaScript”const FN_NAME = "randomUUID";const BASE_STR = [1e7, 1e3, 4e3, 8e3, 1e11].join("-");
const api = crypto;
/*** UUIDを生成します* ブラウザがrandomUUIDをサポートしていない場合はポリフィル実装を実行する* @returns {UUID}*/export function randomUUID() { const api = crypto; if (FN_NAME in api) return api[FN_NAME]();
return BASE_STR.replace(/[018]/g, replacer);}
function replacer(char) { const random = api.getRandomValues(new Uint8Array(1))[0]; const int = Number.parseInt(char); return (int ^ (random & (15 >> (int / 4))).toString(16);}