/
index.js
122 lines (106 loc) · 3 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
'use strict';
var thing = require('core-util-is');
exports = module.exports = {
/**
* Camel cases all properties in an object.
* @param obj
* @param mapFn map keys, return undefined to not include.
*/
camelize: function camelize(obj, mapFn) {
var newobj, keys, k;
if (!mapFn) {
mapFn = function (k) {
return k;
};
}
if (thing.isArray(obj)) {
newobj = [];
for (var i = 0; i < obj.length; i++) {
if (obj[i] && thing.isObject(obj[i])) {
newobj[i] = exports.camelize(obj[i], mapFn);
}
else {
newobj[i] = obj[i];
}
}
}
else if (thing.isObject(obj) && !Buffer.isBuffer(obj)) {
newobj = {};
keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
k = mapFn(keys[i]);
if (!k) {
continue;
}
k = exports.camelCase(k);
newobj[k] = exports.camelize(obj[keys[i]], mapFn);
}
}
else {
newobj = obj;
}
return newobj;
},
/**
* Converts camel case propert names to underscored.
* @param obj
* @param mapFn map keys, return undefined to not include.
*/
underscorify: function (obj, mapFn) {
var newobj, keys, k;
if (!mapFn) {
mapFn = function (k) {
return k;
};
}
if (thing.isArray(obj)) {
newobj = [];
for (var i = 0; i < obj.length; i++) {
if (thing.isObject(obj[i])) {
newobj[i] = exports.underscorify(obj[i], mapFn);
}
else {
newobj[i] = obj[i];
}
}
}
else if (thing.isObject(obj) && !Buffer.isBuffer(obj)) {
newobj = {};
keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
k = mapFn(keys[i]);
if (!k) {
continue;
}
k = exports.underscore(k);
newobj[k] = exports.underscorify(obj[keys[i]], mapFn);
}
}
else {
newobj = obj;
}
return newobj;
},
/**
* Convert foo_bar to fooBar.
* @param gapped
* @returns {string|*}
*/
camelCase: function camelCase(str) {
return str.replace(/([a-z])_(\w)/g, function (g) {
return g[0] + g[2].toUpperCase();
});
},
/**
* Convert fooBar to foo_bar.
* @param humped
* @returns {string|*}
*/
underscore: function underscore(str) {
return str.replace(/([a-z])([A-Z]+)/g, function (g) {
return g.split('').map(function (k) {
return k.toLowerCase();
}).join('_');
});
}
};