Created
March 11, 2024 19:48
-
-
Save arleighdickerson/e1dcb980f0cd7dc3406d87fab62cbcef to your computer and use it in GitHub Desktop.
Utilities for uuids on the client side.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
export namespace uuidUtil { | |
const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi; | |
export function isValidUuid(s: string) { | |
if (!_.isString(s)) { | |
return false; | |
} | |
if (_.isEmpty(s)) { | |
return false; | |
} | |
return regexExp.test(s); | |
} | |
export const randomUuid: () => string = (() => { | |
if (typeof window !== 'undefined' && window.crypto) { | |
if (window.crypto.randomUUID) { | |
return window.crypto.randomUUID(); | |
} | |
if (!!window.crypto.getRandomValues) { | |
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c => | |
// @ts-ignore | |
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16), | |
); | |
} | |
} | |
// noinspection SpellCheckingInspection | |
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { | |
const r = (Math.random() * 16) | 0; | |
const v = String(c) === 'x' ? r : (r & 0x3) | 0x8; | |
return v.toString(16); | |
}); | |
}) as any; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment