camel_case_keys.js 980 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const { camelCase } = require('camel-case');
  3. function getter(key) {
  4. return function() {
  5. return this[key];
  6. };
  7. }
  8. function setter(key) {
  9. return function(value) {
  10. this[key] = value;
  11. };
  12. }
  13. function toCamelCase(str) {
  14. let prefixLength = -1;
  15. while (str[++prefixLength] === '_');
  16. if (!prefixLength) {
  17. return camelCase(str);
  18. }
  19. return str.substring(0, prefixLength) + camelCase(str.substring(prefixLength));
  20. }
  21. function camelCaseKeys(obj) {
  22. if (typeof obj !== 'object') throw new TypeError('obj must be an object!');
  23. const keys = Object.keys(obj);
  24. const result = {};
  25. for (const oldKey of keys) {
  26. const newKey = toCamelCase(oldKey);
  27. result[newKey] = obj[oldKey];
  28. if (newKey !== oldKey) {
  29. Object.defineProperty(result, oldKey, {
  30. get: getter(newKey),
  31. set: setter(newKey),
  32. configurable: true,
  33. enumerable: true
  34. });
  35. }
  36. }
  37. return result;
  38. }
  39. module.exports = camelCaseKeys;