Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Huauauaa committed Sep 13, 2024
1 parent 42c1ae9 commit c510db0
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/util/__tests__/case.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { toCamel } from '../case';

test('toCamel', () => {
expect(toCamel(null)).toBe(null);
expect(toCamel(undefined)).toBe(undefined);
expect(toCamel(1)).toBe(1);
expect(toCamel(0)).toBe(0);
expect(toCamel('first_name')).toBe('firstName');
expect(toCamel(true)).toBe(true);
expect(toCamel(true)).toBe(true);
expect(toCamel([])).toStrictEqual([]);
expect(toCamel({})).toStrictEqual({});
expect(toCamel({ firstName: null })).toStrictEqual({
firstName: null,
});
expect(toCamel({ firstName: undefined })).toStrictEqual({
firstName: undefined,
});
expect(toCamel({ firstName: 'Harvey' })).toStrictEqual({
firstName: 'Harvey',
});
expect(toCamel({ first_name: 'Harvey' })).toStrictEqual({
firstName: 'Harvey',
});
expect(toCamel({ First_Name: 'Harvey' })).toStrictEqual({
firstName: 'Harvey',
});
expect(toCamel([{ first_name: 'Harvey' }])).toStrictEqual([
{
firstName: 'Harvey',
},
]);
expect(
toCamel({ first_name: 'Harvey', favorite_thing: ['reading'] }),
).toStrictEqual({
firstName: 'Harvey',
favoriteThing: ['reading'],
});
});
27 changes: 27 additions & 0 deletions src/util/case.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import _ from 'lodash';

function camelCase(str) {
return _.camelCase(str);
// return str.replace(/_([a-z])/g, (p, m) => m.toUpperCase());
}

export function toCamel(data) {
if (typeof data === 'string') {
return camelCase(data);
}
if (typeof data !== 'object' || !data) {
return data;
}
if (Array.isArray(data)) {
return data.map((item) => toCamel(item));
}

return Object.keys(data).reduce((res, key) => {
let value = data[key];
if (typeof value === 'object') {
value = toCamel(value);
}
res[camelCase(key)] = value;
return res;
}, {});
}

0 comments on commit c510db0

Please sign in to comment.