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