Skip to content

Commit

Permalink
💥 NEW: Refactor snakeToCamel function to use a more efficient regex p…
Browse files Browse the repository at this point in the history
…attern
  • Loading branch information
Shaban-Eissa committed Jun 7, 2024
1 parent d251d79 commit 89d2a2f
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions 79.convert-snake_case-to-camelCase.md
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)

0 comments on commit 89d2a2f

Please sign in to comment.