-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathindex.js
42 lines (35 loc) · 1.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'use strict'
const map = require('map-obj')
const { snakeCase } = require('snake-case')
const PlainObjectConstructor = {}.constructor
module.exports = function (obj, options) {
if (Array.isArray(obj)) {
if (obj.some(item => item.constructor !== PlainObjectConstructor)) {
throw new Error('obj must be array of plain objects')
}
} else {
if (obj.constructor !== PlainObjectConstructor) {
throw new Error('obj must be an plain object')
}
}
options = Object.assign({ deep: true, exclude: [], parsingOptions: {} }, options)
return map(obj, function (key, val) {
return [
matches(options.exclude, key) ? key : snakeCase(key, options.parsingOptions),
val,
mapperOptions(key, val, options)
]
}, options)
}
function matches (patterns, value) {
return patterns.some(function (pattern) {
return typeof pattern === 'string'
? pattern === value
: pattern.test(value)
})
}
function mapperOptions (key, val, options) {
return options.shouldRecurse
? { shouldRecurse: options.shouldRecurse(key, val) }
: undefined
}