-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
44 lines (39 loc) · 1.12 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
43
44
import mergeWith from 'lodash-es/mergeWith.js'
import isArguments from 'lodash-es/isArguments.js'
// mapValues, but modify the original object
const mapValues = (object, iteratee) => {
Object.keys(object).forEach(key => {
object[key] = iteratee(object[key], key, object)
})
return object
}
// marker object to return undefined from mergeWith, without it triggering the default merge algorithm
const UNDEFINED = new Object()
// transform UNDEFINED to undefined
const toUndefined = v => (
v === UNDEFINED
? undefined
: (
Array.isArray(v)
? v.map(toUndefined)
: (
typeof v === 'object' && v !== null
? mapValues(v, toUndefined)
: v
)
)
)
export const merge = (...args) => mapValues(
mergeWith(
...args,
(a, b) => {
if (b === undefined) { return UNDEFINED }
if (Array.isArray(a) || Array.isArray(b)) { return undefined }
if (isArguments(a) || isArguments(b)) { return undefined }
if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null) { return merge(a, b) }
return undefined
}
),
toUndefined
)
export default merge