11import { hash } from './hash'
22
3+ /**
4+ * 根据正则规则将代码中的匹配部分转换为哈希值,并返回还原函数
5+ *
6+ * 这个函数主要用于需要临时替换代码中某些部分,处理后再还原的场景。
7+ * 例如:在代码格式化、语法解析等过程中保护特定的代码片段不被修改。
8+ *
9+ * @param {string } code - 需要处理的原始代码字符串
10+ * @param {RegExp[] } rules - 正则表达式数组,用于匹配需要转换的代码片段
11+ * @returns {[string, (newCode: string) => string] } 返回一个元组:
12+ * - 第一个元素:转换后的代码字符串(匹配的部分被替换为哈希值)
13+ * - 第二个元素:还原函数,接收处理后的代码,将哈希值还原为原始内容
14+ *
15+ * @example
16+ * ```typescript
17+ * const code = 'const str = "hello world"; const num = 123;';
18+ * const rules = [/"[^"]*"/g, /\d+/g]; // 匹配字符串和数字
19+ *
20+ * const [transformed, restore] = transformWithBack(code, rules);
21+ * console.log(transformed); // 'const str = hash1; const num = hash2;'
22+ *
23+ * // 对转换后的代码进行一些处理...
24+ * const processedCode = transformed.replace(/const/g, 'let');
25+ *
26+ * // 还原原始内容
27+ * const finalCode = restore(processedCode);
28+ * console.log(finalCode); // 'let str = "hello world"; let num = 123;'
29+ * ```
30+ */
331export function transformWithBack (
432 code : string ,
533 rules : RegExp [ ] ,
@@ -8,11 +36,12 @@ export function transformWithBack(
836 let result = code
937 for ( const rule of rules ) {
1038 result = result . replace ( rule , ( all ) => {
11- if ( hashMap . has ( code ) )
12- return hashMap . get ( code ) !
39+ // 注意:这里应该检查 hashMap.has(all) 而不是 hashMap.has(code)
40+ if ( hashMap . has ( all ) )
41+ return hashMap . get ( all ) !
1342
1443 const _hash = hash ( all )
15- hashMap . set ( code , _hash )
44+ hashMap . set ( all , _hash ) // 这里也应该是 all 而不是 code
1645 return _hash
1746 } )
1847 }
0 commit comments