Skip to content

Commit

Permalink
Merge pull request #48 from segayuu/refactor-camel-case-keys
Browse files Browse the repository at this point in the history
Refactor: camel_case_keys.js
  • Loading branch information
segayuu committed Nov 30, 2018
2 parents 6e5f1c4 + cbd6a18 commit faa875c
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions lib/camel_case_keys.js
Expand Up @@ -2,8 +2,6 @@

const camelCase = require('camel-case');

const rPrefixUnderscore = /^(_+)/;

function getter(key) {
return function() {
return this[key];
Expand All @@ -16,30 +14,32 @@ function setter(key) {
};
}

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, len = keys.length; i < len; i++) {
const key = keys[i];
const value = obj[key];
const match = key.match(rPrefixUnderscore);
let newKey;

if (match) {
const underscore = match[1];
newKey = underscore + camelCase(key.substring(underscore.length));
} else {
newKey = camelCase(key);
}
for (let i = 0; i < length; i++) {
const oldKey = keys[i];
const newKey = toCamelCase(oldKey);

result[newKey] = obj[oldKey];

if (newKey === key) {
result[key] = value;
} else {
result[newKey] = value;
Object.defineProperty(result, key, {
if (newKey !== oldKey) {
Object.defineProperty(result, oldKey, {
get: getter(newKey),
set: setter(newKey),
configurable: true,
Expand Down

0 comments on commit faa875c

Please sign in to comment.