Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: camel_case_keys.js #48

Merged
merged 4 commits into from Nov 30, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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