/
camel_case_keys.js
54 lines (41 loc) · 1.01 KB
/
camel_case_keys.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
'use strict';
const camelCase = require('camel-case');
function getter(key) {
return function() {
return this[key];
};
}
function setter(key) {
return function(value) {
this[key] = value;
};
}
function toCamelCase(str) {
let prefixLength = -1;
while (str[++prefixLength] === '_');
if (!prefixLength) {
return camelCase(str);
}
return str.substring(0, prefixLength) + camelCase(str.substring(prefixLength));
}
function camelCaseKeys(obj) {
if (typeof obj !== 'object') throw new TypeError('obj must be an object!');
const keys = Object.keys(obj);
const { length } = keys;
const result = {};
for (let i = 0; i < length; i++) {
const oldKey = keys[i];
const newKey = toCamelCase(oldKey);
result[newKey] = obj[oldKey];
if (newKey !== oldKey) {
Object.defineProperty(result, oldKey, {
get: getter(newKey),
set: setter(newKey),
configurable: true,
enumerable: true
});
}
}
return result;
}
module.exports = camelCaseKeys;