-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
💥 NEW: Refactor snakeToCamel function to use a more efficient regex p…
…attern
- Loading branch information
1 parent
d251d79
commit 89d2a2f
Showing
1 changed file
with
84 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
# 79. convert snake_case to camelCase | ||
|
||
### Problem | ||
|
||
https://bigfrontend.dev/problem/convert-snake_case-to-camelCase | ||
|
||
# | ||
|
||
### Problem Description | ||
|
||
Do you prefer [snake_case](https://en.wikipedia.org/wiki/Snake_case) or [camelCase](https://en.wikipedia.org/wiki/Camel_case) ? | ||
|
||
Anyway, please create a function to convert snake_case to camcelCase. | ||
|
||
```js | ||
snakeToCamel('snake_case'); | ||
// 'snakeCase' | ||
snakeToCamel('is_flag_on'); | ||
// 'isFlagOn' | ||
snakeToCamel('is_IOS_or_Android'); | ||
// 'isIOSOrAndroid' | ||
snakeToCamel('_first_underscore'); | ||
// '_firstUnderscore' | ||
snakeToCamel('last_underscore_'); | ||
// 'lastUnderscore_' | ||
snakeToCamel('_double__underscore_'); | ||
// '_double__underscore_' | ||
``` | ||
|
||
contiguous underscore `__`, leading underscore `_a`, and trailing underscore `a_` should be kept untouched. | ||
|
||
# | ||
|
||
### Solution | ||
|
||
```js | ||
/** | ||
* @param {string} str | ||
* @return {string} | ||
*/ | ||
function snakeToCamel(str) { | ||
return str.replace(/[a-z]_[a-z]/gi, (match) => { | ||
return match[0] + match[2].toUpperCase(); | ||
}); | ||
} | ||
``` | ||
|
||
# | ||
|
||
### Refactored Solution | ||
|
||
```js | ||
/** | ||
* @param {string} str | ||
* @return {string} | ||
*/ | ||
function snakeToCamel(str) { | ||
return str.replace(/([^_])_([^_])/g, (_, before, after) => { | ||
return before + after.toUpperCase(); | ||
}); | ||
} | ||
``` | ||
|
||
# | ||
|
||
### Solution with Lookbehind | ||
|
||
```js | ||
/** | ||
* @param {string} str | ||
* @return {string} | ||
*/ | ||
function snakeToCamel(str) { | ||
return str.replace(/(?<=[a-z])_[a-z]/gi, (match) => { | ||
return match[1].toUpperCase(); | ||
}); | ||
} | ||
``` | ||
|
||
# | ||
|
||
### Reference | ||
|
||
[Problem Discuss](https://bigfrontend.dev/problem/convert-snake_case-to-camelCase/discuss) |