-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (66 loc) · 1.64 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* parse
* @param {object, array} obj
* @returns {*}
*/
function parse (obj) {
return isObject(obj) ? (Object.assign(
{},
...Object.keys(obj).map(item => (
{[convert(item)]: (isObject(obj[item])) ? parse(obj[item]) : (Array.isArray(obj[item]) ? parseArray(obj[item]) : obj[item])})
)
)) : (parseArray(obj));
}
/**
* parseArray
* @param {array} arr
* @return {array}
*/
function parseArray (arr) {
return arr.map(item => (isObject(item) ? parse(item) : item));
}
/**
* isObject
* @param {*} val
* @returns {boolean}
*/
function isObject (val) {
return val !== null && typeof val === 'object' && !Array.isArray(val) && !val.then;
}
/**
* isPromise
* @param {*} val
* @returns {boolean}
*/
function isPromise (val) {
return !!val && (typeof val === 'object' || typeof val === 'function') && typeof val.then === 'function';
}
/**
* convert
* @param {string} str
* @returns {string}
*/
function convert (str) {
let arr = str.split(/[_]/);
let newStr = '';
for (let i = 1; i < arr.length; i++) {
newStr += arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr[0] + newStr;
}
/**
* propsToCamelCase
* @param {object, array, promise} props
* @param {function} props.then
* @returns {*}
*/
export default function propsToCamelCase (props) {
try {
if (!isPromise(props) && !isObject(props) && !Array.isArray(props)) {
throw new TypeError('Function takes only objects, arrays and promises');
}
return isObject(props) ? parse(props) : (Array.isArray(props) ? parseArray(props) : props.then(res => (new Promise(resolve => (resolve(parse(res)))))));
} catch (err) {
return err;
}
}