my pkgs monorepo
1export function isValidTid(tid: string): boolean {
2 const tidPattern = /^[a-zA-Z0-9]{12,16}$/;
3 return tidPattern.test(tid);
4}
5
6export function isValidDid(did: string): boolean {
7 const didPattern = /^did:[a-z]+:[a-zA-Z0-9._:-]+$/;
8 return didPattern.test(did);
9}
10
11export function truncateText(text: string, maxLength: number, ellipsis = '...'): string {
12 if (text.length <= maxLength) return text;
13 return text.slice(0, maxLength - ellipsis.length).trim() + ellipsis;
14}
15
16export function escapeHtml(text: string): string {
17 const div = typeof document !== 'undefined' ? document.createElement('div') : null;
18 if (div) {
19 div.textContent = text;
20 return div.innerHTML;
21 }
22 return text
23 .replace(/&/g, '&')
24 .replace(/</g, '<')
25 .replace(/>/g, '>')
26 .replace(/"/g, '"')
27 .replace(/'/g, ''');
28}
29
30export function getInitials(name: string): string {
31 const words = name.trim().split(/\s+/);
32 if (words.length === 1) return words[0].charAt(0).toUpperCase();
33 return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();
34}
35
36export function debounce<T extends (...args: any[]) => any>(
37 func: T,
38 delay: number
39): (...args: Parameters<T>) => void {
40 let timeoutId: ReturnType<typeof setTimeout>;
41 return (...args: Parameters<T>) => {
42 clearTimeout(timeoutId);
43 timeoutId = setTimeout(() => func(...args), delay);
44 };
45}
46
47export function throttle<T extends (...args: any[]) => any>(
48 func: T,
49 limit: number
50): (...args: Parameters<T>) => void {
51 let inThrottle: boolean;
52 return (...args: Parameters<T>) => {
53 if (!inThrottle) {
54 func(...args);
55 inThrottle = true;
56 setTimeout(() => (inThrottle = false), limit);
57 }
58 };
59}