Skip to content

Commit 561eae4

Browse files
committed
feat: update camelize function to support PascalCase and enhance transformWithBack documentation
1 parent 8fabc77 commit 561eae4

File tree

2 files changed

+44
-8
lines changed

2 files changed

+44
-8
lines changed

src/string/camelize.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
/**
2-
* 将xx-xx转为xxXx 大驼峰格式
3-
* @param { string } s 字符串
4-
* @returns string
2+
* 将xx-xx转为xxXx小驼峰或XxXx大驼峰格式
3+
* @param {string} s 字符串
4+
* @param {boolean} [pascalCase] 是否返回大驼峰格式(PascalCase)
5+
* @returns {string} 驼峰格式字符串
56
*/
6-
export function camelize(s: string): string {
7-
return s.replace(/-(\w)/g, (all, letter) => letter.toUpperCase())
7+
export function camelize(s: string, pascalCase?: boolean): string {
8+
const camelized = s.replace(/-(\w)/g, (_all, letter) => letter.toUpperCase())
9+
10+
if (pascalCase) {
11+
return camelized.charAt(0).toUpperCase() + camelized.slice(1)
12+
}
13+
14+
return camelized
815
}

src/string/transformWithBack.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,33 @@
11
import { 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+
*/
331
export 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

Comments
 (0)