合并含public函数的两个字符串并去除重复函数
合并含重复public函数的字符串并去重
我有两个包含函数的字符串,需要合并,但其中存在重复的函数。这些函数均以public开头,无嵌套函数且函数名唯一。
示例代码
let str1 = ` public getPetById(petId: number, header: {}) { return this.http.get(this.baseUrl + pet/${petId}\`, { headers: header }); } public updatePetWithForm(petId: number, body: {name?: string, status?: string}, header: {}) { return this.http.post(this.baseUrl + \`/pet/${petId}\`, body, { headers: header }); } `; let str2 = ` public getPetById(petId: number, header: {}) { return this.http.get(this.baseUrl + \`/pet/${petId}\`, { headers: header }); } public deletePet(petId: number, header: {api_key: string}) { return this.http.delete(this.baseUrl + \`/pet/${petId}\`, { headers: header }); } `;
当前的重复检测方法
function hasDuplicates(array: any[]) { return (new Set(array)).size !== array.length; } hasDuplicates(combinedString.match(/(?<=public ).+(?=[$\(])/gm));
期望结果
`public getPetById(petId: number, header: {}) { return this.http.get(this.baseUrl + pet/${petId}\`, { headers: header }); } public updatePetWithForm(petId: number, body: {name?: string, status?: string}, header: {}) { return this.http.post(this.baseUrl + \`/pet/${petId}\`, body, { headers: header }); } public deletePet(petId: number, header: {api_key: string}) { return this.http.delete(this.baseUrl + \`/pet/${petId}\`, { headers: header }); }`
解决方案
可以通过提取完整函数→按函数名去重→拼接结果的步骤实现:
- 合并两个输入字符串;
- 用正则提取所有完整的
public函数(利用无嵌套特性,确保每个匹配都是独立函数); - 用
Map存储函数,以函数名为键实现去重(可选择保留第一个或最后一个出现的函数); - 拼接去重后的函数得到最终字符串。
完整实现代码:
// 合并两个字符串 const combined = str1 + str2; // 提取所有完整的public函数(适配缩进、换行,无嵌套场景下准确分割) const functions = combined.match(/^\s*public\s+.+?(?=\s*public|$)/gsm) || []; // 用Map去重,保留第一个出现的同名函数 const uniqueFuncMap = new Map<string, string>(); functions.forEach(func => { // 提取函数名 const funcNameMatch = func.match(/public\s+(\w+)\(/); if (funcNameMatch) { const funcName = funcNameMatch[1]; if (!uniqueFuncMap.has(funcName)) { // 去除函数前后多余的空白字符,让结果更整洁 uniqueFuncMap.set(funcName, func.trim()); } } }); // 拼接成最终的去重后字符串 const finalResult = Array.from(uniqueFuncMap.values()).join('\n'); console.log(finalResult);
代码说明
- 正则
/^\s*public\s+.+?(?=\s*public|$)/gsm:^匹配行首,\s*忽略开头缩进,public定位函数起始,.+?(?=\s*public|$)匹配到下一个public或字符串结尾为止,gsm确保全局匹配、跨行匹配、多行模式生效; - 使用
Map而非普通对象存储,避免函数名与对象内置属性冲突; - 若要保留最后一个出现的同名函数,只需删除
if (!uniqueFuncMap.has(funcName))判断,直接执行uniqueFuncMap.set(funcName, func.trim())即可。
内容的提问来源于stack exchange,提问作者Matthias VdC
相关产品推荐
相关产品推荐

