-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (48 loc) · 1.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
camelCase
snake_case
kebab-case
PascalCase
*/
// Reference: https://matthiashager.com/converting-snake-case-to-camel-case-object-keys-with-javascript
const isArray = function (a) {
return Array.isArray(a);
};
const isObject = function (o) {
return o === Object(o) && !isArray(o) && typeof o !== 'function';
};
/**
*
* @param {string} s
* @returns {string} return string in camelCae
*/
const toCamel = (s = '') => {
if (typeof s !== 'string')
throw new Error('toCamel should receive only strings');
if (s.startsWith('-' || '_')) s = s.slice(1);
if (s.endsWith('-' || '_')) s = s.slice(0, s.length - 1);
return s.replace(/([-_][a-z])/gi, ($1, rest) => {
return $1.toUpperCase().replace('-', '').replace('_', '');
});
};
/**
*
* @param {object | Object []} o
* @returns {object | Object []} retorn object or array of object with keys in camelCase
*/
const keysToCamel = function (o) {
if (isObject(o)) {
const n = {};
Object.keys(o).forEach((k) => {
n[toCamel(k)] = keysToCamel(o[k]);
});
return n;
}
if (isArray(o)) {
return o.map((i) => {
return keysToCamel(i);
});
}
return o;
};
module.exports = { keysToCamel, toCamel };