Skip to content

Instantly share code, notes, and snippets.

@arleighdickerson
Created March 11, 2024 19:48
Show Gist options
  • Save arleighdickerson/e1dcb980f0cd7dc3406d87fab62cbcef to your computer and use it in GitHub Desktop.
Save arleighdickerson/e1dcb980f0cd7dc3406d87fab62cbcef to your computer and use it in GitHub Desktop.
Utilities for uuids on the client side.
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