(baseName: string, existingNames: string[])
| 9 | * e.g., "新对话" -> "新对话 (1)" -> "新对话 (2)" |
| 10 | */ |
| 11 | export function generateUniqueName(baseName: string, existingNames: string[]): string { |
| 12 | // Check if base name is available |
| 13 | if (!existingNames.includes(baseName)) { |
| 14 | return baseName |
| 15 | } |
| 16 | |
| 17 | // Find all names matching pattern "baseName" or "baseName (n)" |
| 18 | const pattern = new RegExp(`^${escapeRegExp(baseName)}(?: \\((\\d+)\\))?$`) |
| 19 | let maxNumber = 0 |
| 20 | |
| 21 | for (const name of existingNames) { |
| 22 | const match = name.match(pattern) |
| 23 | if (match) { |
| 24 | const num = match[1] ? parseInt(match[1], 10) : 0 |
| 25 | if (num > maxNumber) { |
| 26 | maxNumber = num |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | return `${baseName} (${maxNumber + 1})` |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Escape special regex characters in a string |
no test coverage detected