@ezmockup/ezuuid
Version:
A simple and easy-to-use UUID generation and processing library.
53 lines (43 loc) • 2.08 kB
text/typescript
// UUID 工具库
import crypto from 'crypto';
/** UUID最小值(全0) */
export const Min = '00000000-0000-0000-0000-000000000000';
/** UUID最大值(全f) */
export const Max = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
/** 生成一个UUID v1(基于时间戳) */
export function V1(): string {
// 简易实现,非全RFC兼容,仅供一般用途
const now = Date.now();
const time = now.toString(16).padStart(12, '0');
const random = crypto.randomBytes(10).toString('hex');
return `${time.slice(0, 8)}-${time.slice(8, 12)}-1${random.slice(0, 3)}-a${random.slice(3, 3 + 3)}-${random.slice(6, 18)}`;
}
/** 生成一个UUID v3(基于命名空间和名字,MD5) */
export function V3(name: string, namespace: string): string {
const ns = namespace.replace(/-/g, '');
const hash = crypto.createHash('md5').update(Buffer.from(ns + name)).digest('hex');
return `${hash.substr(0, 8)}-${hash.substr(8, 4)}-3${hash.substr(13, 3)}-a${hash.substr(16, 3)}-${hash.substr(19, 12)}`;
}
/** 生成一个UUID v4(随机) */
export function V4(): string {
// 生成符合RFC4122 v4的UUID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/** 生成一个UUID v5(基于命名空间和名字,SHA1) */
export function V5(name: string, namespace: string): string {
const ns = namespace.replace(/-/g, '');
const hash = crypto.createHash('sha1').update(Buffer.from(ns + name)).digest('hex');
return `${hash.substr(0, 8)}-${hash.substr(8, 4)}-5${hash.substr(13, 3)}-a${hash.substr(16, 3)}-${hash.substr(19, 12)}`;
}
/** 校验UUID格式(v4) */
export function validateUUID(uuid: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid);
}
/** 格式化UUID字符串(去除多余空格并转小写) */
export function formatUUID(uuid: string): string {
return uuid.trim().toLowerCase();
}