index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const mapObj = require('map-obj');
  3. const camelCase = require('camelcase');
  4. const QuickLru = require('quick-lru');
  5. const has = (array, key) => array.some(x => {
  6. if (typeof x === 'string') {
  7. return x === key;
  8. }
  9. x.lastIndex = 0;
  10. return x.test(key);
  11. });
  12. const cache = new QuickLru({maxSize: 100000});
  13. // Reproduces behavior from `map-obj`
  14. const isObject = value =>
  15. typeof value === 'object' &&
  16. value !== null &&
  17. !(value instanceof RegExp) &&
  18. !(value instanceof Error) &&
  19. !(value instanceof Date);
  20. const camelCaseConvert = (input, options) => {
  21. if (!isObject(input)) {
  22. return input;
  23. }
  24. options = {
  25. deep: false,
  26. pascalCase: false,
  27. ...options
  28. };
  29. const {exclude, pascalCase, stopPaths, deep} = options;
  30. const stopPathsSet = new Set(stopPaths);
  31. const makeMapper = parentPath => (key, value) => {
  32. if (deep && isObject(value)) {
  33. const path = parentPath === undefined ? key : `${parentPath}.${key}`;
  34. if (!stopPathsSet.has(path)) {
  35. value = mapObj(value, makeMapper(path));
  36. }
  37. }
  38. if (!(exclude && has(exclude, key))) {
  39. const cacheKey = pascalCase ? `${key}_` : key;
  40. if (cache.has(cacheKey)) {
  41. key = cache.get(cacheKey);
  42. } else {
  43. const ret = camelCase(key, {pascalCase});
  44. if (key.length < 100) { // Prevent abuse
  45. cache.set(cacheKey, ret);
  46. }
  47. key = ret;
  48. }
  49. }
  50. return [key, value];
  51. };
  52. return mapObj(input, makeMapper(undefined));
  53. };
  54. module.exports = (input, options) => {
  55. if (Array.isArray(input)) {
  56. return Object.keys(input).map(key => camelCaseConvert(input[key], options));
  57. }
  58. return camelCaseConvert(input, options);
  59. };