Skip to content

Commit

Permalink
feat: add camel to snake and snake to camel in utils
Browse files Browse the repository at this point in the history
  • Loading branch information
danimuller20 committed Sep 26, 2023
1 parent 7d1f723 commit 0cfb8a2
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"arrowParens": "avoid",
"arrowParens": "always",
"bracketLine": true,
"printWidth": 80,
"singleQuote": true,
"tabWidth": 2,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false
}
34 changes: 34 additions & 0 deletions docs/pages/utils/camelToSnake.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## `camelToSnakeCase(camel: string | string[]): string | string[]`

This utility function is designed to convert camelCase strings or arrays of camelCase strings to snake_case.

### Parameters

- `camel` (string | string[]): The input string or array of strings in camelCase to be converted to snake_case.

### Return Value

- Returns a new string or an array of strings with camelCase converted to snake_case.

### Examples

#### Basic Example

```javascript
import camelToSnakeCase from '../src';

const camelString = 'myVariableName';
const snakeString = camelToSnakeCase(camelString);
console.log(snakeString);
// Output: 'my_variable_name'


// Handling an Array of CamelCase Strings

const camelArray = ['firstName', 'lastName', 'emailAddress'];
const snakeArray = camelToSnakeCase(camelArray);
console.log(snakeArray);
// Output: ['first_name', 'last_name', 'email_address']

```

91 changes: 91 additions & 0 deletions docs/pages/utils/snakeToCamel.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
## `snakeToCamel(obj: object): object`

This utility function is designed to transform keys of an object from snake_case to camelCase. It also handles nested objects and arrays of objects.

### Parameters

- `obj` (object): The object to be transformed.

### Return Value

- Returns a new object with keys converted from snake_case to camelCase. The values of the object are preserved.

### Examples

#### Basic Example

```javascript
import snakeToCamel from '../src';

const inputObject = {
user_name: 'John',
age: 30,
is_active: true,
};

const transformedObject = snakeToCamel(inputObject);
console.log(transformedObject);
// Output:
// {
// userName: 'John',
// age: 30,
// isActive: true,
// }
```

#### Handling Nested Objects

```javascript
import snakeToCamel from '../src';

const nestedInputObject = {
person_info: {
first_name: 'Alice',
last_name: 'Johnson',
},
is_active: true,
};

const transformedNestedObject = snakeToCamel(nestedInputObject);
console.log(transformedNestedObject);
// Output:
// {
// personInfo: {
// firstName: 'Alice',
// lastName: 'Johnson',
// },
// isActive: true,
// }
```

#### Handling Arrays of Objects

```javascript
import snakeToCamel from '../src';

const arrayOfObjects = [
{
first_name: 'Alice',
last_name: 'Johnson',
},
{
first_name: 'Bob',
last_name: 'Smith',
},
];

const transformedArray = snakeToCamel(arrayOfObjects);
console.log(transformedArray);
// Output:
// [
// {
// firstName: 'Alice',
// lastName: 'Johnson',
// },
// {
// firstName: 'Bob',
// lastName: 'Smith',
// },
// ]

```
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export { default as normalizeSocialNumber } from './normalizers/normalizeSocialN
export { default as maskString } from './utils/maskString';
export { default as stripNumbers } from './utils/stripNumbers';
export { default as getStates } from './utils/getStates';
export { default as snakeToCamel } from './utils/snakeToCamel';
export { default as camelToSnake } from './utils/camelToSnake';

// validations
export { default as isCpf } from './validations/isCpf';
Expand Down
9 changes: 9 additions & 0 deletions src/utils/camelToSnake.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default function camelToSnakeCase(camel: string | string[]): string | string[] {
const toSnake = (str: string) => str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);

if (typeof camel === 'string') {
return toSnake(camel);
}

return camel.map((c) => toSnake(c));
}
31 changes: 31 additions & 0 deletions src/utils/snakeToCamel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function toCamel(str: string) {
return str.replace(/([-_][a-z])/gi, ($1: string) => {
const upperCase = $1.toUpperCase().replace('-', '').replace('_', '');
return upperCase;
});
}

function isObject(obj: object) {
return (
obj === Object(obj) && !Array.isArray(obj) && typeof obj !== 'function'
);
}

export default function snakeToCamel(obj: object): object {
if (isObject(obj)) {
const n: any = {};

Object.keys(obj).forEach((k: string) => {
const converted = toCamel(k);

n[converted as keyof typeof n] = snakeToCamel(obj[k as keyof typeof obj]);
});

return n;
}
if (Array.isArray(obj)) {
return obj.map((i: any) => snakeToCamel(i));
}

return obj;
}
17 changes: 17 additions & 0 deletions tests/camelToSnake.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { camelToSnake } from '../src'; // Replace with the actual path to your file

describe('camelToSnakeCase', () => {
it('should convert a camelCase string to snake_case', () => {
const camelString = 'myVariableName';
const expectedSnakeString = 'my_variable_name';

expect(camelToSnake(camelString)).toEqual(expectedSnakeString);
});

it('should convert an array of camelCase strings to snake_case', () => {
const camelArray = ['firstName', 'lastName', 'emailAddress'];
const expectedSnakeArray = ['first_name', 'last_name', 'email_address'];

expect(camelToSnake(camelArray)).toEqual(expectedSnakeArray);
});
});
1 change: 0 additions & 1 deletion tests/isCpf.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,3 @@ describe('test isCPF', () => {
expect(isCpf('02213015287')).toBe(false);
});
});

67 changes: 67 additions & 0 deletions tests/snakeToCamel.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import 'jest';

import { snakeToCamel } from '../src';

describe('snakeToCamel', () => {
it('should convert object keys from snake_case to camelCase', () => {
const input = {
user_name: 'John',
age: 30,
is_active: true,
};

const expectedOutput = {
userName: 'John',
age: 30,
isActive: true,
};

expect(snakeToCamel(input)).toEqual(expectedOutput);
});

it('should handle arrays of objects.', () => {
const input = [
{
first_name: 'Alice',
last_name: 'Johnson',
},
{
first_name: 'Bob',
last_name: 'Smith',
},
];

const expectedOutput = [
{
firstName: 'Alice',
lastName: 'Johnson',
},
{
firstName: 'Bob',
lastName: 'Smith',
},
];

expect(snakeToCamel(input)).toEqual(expectedOutput);
});

it('should handle nested objects', () => {
const input = {
person_info: {
first_name: 'Alice',
last_name: 'Johnson',
},
is_active: true,
};

const expectedOutput = {
personInfo: {
firstName: 'Alice',
lastName: 'Johnson',
},
isActive: true,
};

expect(snakeToCamel(input)).toEqual(expectedOutput);
});
});

0 comments on commit 0cfb8a2

Please sign in to comment.