返回 AiToEarn
common.ts
根目录 / project / aitoearn-web / src / utils / common.ts
1 /**
2 * common.ts - 跨业务基础工具函数
3 */
4
5 /**
6 * 生成唯一 ID。
7 */
8 export function generateUUID(): string {
9 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
10 const randomValue = (Math.random() * 16) | 0
11 const uuidValue = char === 'x' ? randomValue : (randomValue & 0x3) | 0x8
12 return uuidValue.toString(16)
13 })
14 }
15
16 /**
17 * 等待指定毫秒数。
18 */
19 export function sleep(ms: number) {
20 return new Promise<void>(resolve => setTimeout(resolve, ms))
21 }
22
23 /**
24 * 获取文件路径中的文件名和后缀。
25 */
26 export function getFilePathName(path: string) {
27 if (!path) {
28 return {
29 filename: '',
30 suffix: '',
31 }
32 }
33
34 const pathByBackslash = path.split('\\')
35 const pathWithoutBackslash = pathByBackslash[pathByBackslash.length - 1]
36 const pathBySlash = pathWithoutBackslash.split('/')
37 const filename = pathBySlash[pathBySlash.length - 1]
38
39 return {
40 filename,
41 suffix: filename.split('.')[filename.split('.').length - 1],
42 }
43 }
44
45 /**
46 * 提取字符串中的话题,并返回去除话题后的文本。
47 */
48 export function parseTopicString(input: string): {
49 topics: string[]
50 cleanedString: string
51 } {
52 const extractedParts = input.match(/#(\S+)/g) || []
53 let cleanedString = input
54
55 extractedParts.forEach((part) => {
56 cleanedString = cleanedString.replace(part, '').trim()
57 })
58
59 const topics = extractedParts.map((part) => {
60 const match = part.match(/#(\S+)/)
61 return match ? match[1] : ''
62 })
63
64 return { topics, cleanedString }
65 }
66
66 lines TYPESCRIPT