Skip to content

Commit e494dd8

Browse files
committed
simplify snakeToCamelCase() implementation
1 parent f34fd60 commit e494dd8

File tree

1 file changed

+4
-18
lines changed

1 file changed

+4
-18
lines changed

src/utils.ts

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,12 @@
11
/**
22
* Converts snake_case to camelCase
33
* @param {string} input - snake_case string
4-
* @param {string} exclude - `input` that contains `exclude` will be returned unmodified
54
* @returns {string} - camelCase string
65
*/
7-
export function snakeToCamelCase(input: string, exclude = '-'): string {
8-
// Return the input string unchanged if there are no underscores
9-
// or it includes the `exclude` character.
10-
if (!input.includes('_') || input.includes(exclude)) {
11-
return input;
12-
}
13-
// remove trailing/leading underscores
14-
let output = input.replace(/^_+/, '').replace(/_+$/, '');
15-
let currentIndex = output.indexOf('_');
16-
while (currentIndex !== -1) {
17-
output =
18-
output.slice(0, currentIndex) +
19-
output[currentIndex + 1].toUpperCase() +
20-
output.slice(currentIndex + 2);
21-
currentIndex = output.indexOf('_', currentIndex);
22-
}
23-
return output;
6+
export function snakeToCamelCase(input: string): string {
7+
return input.replace(/_+(\w?)/g, (_, p, o) =>
8+
o === 0 ? p : p.toUpperCase()
9+
);
2410
}
2511

2612
const isObject = (value: unknown) =>

0 commit comments

Comments
 (0)