1 | var isMergeableObject = require('is-mergeable-object')
|
2 |
|
3 | function emptyTarget(val) {
|
4 | return Array.isArray(val) ? [] : {}
|
5 | }
|
6 |
|
7 | function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
|
8 | var clone = !optionsArgument || optionsArgument.clone !== false
|
9 |
|
10 | return (clone && isMergeableObject(value))
|
11 | ? deepmerge(emptyTarget(value), value, optionsArgument)
|
12 | : value
|
13 | }
|
14 |
|
15 | function defaultArrayMerge(target, source, optionsArgument) {
|
16 | return target.concat(source).map(function(element) {
|
17 | return cloneUnlessOtherwiseSpecified(element, optionsArgument)
|
18 | })
|
19 | }
|
20 |
|
21 | function mergeObject(target, source, optionsArgument) {
|
22 | var destination = {}
|
23 | if (isMergeableObject(target)) {
|
24 | Object.keys(target).forEach(function(key) {
|
25 | destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument)
|
26 | })
|
27 | }
|
28 | Object.keys(source).forEach(function(key) {
|
29 | if (!isMergeableObject(source[key]) || !target[key]) {
|
30 | destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument)
|
31 | } else {
|
32 | destination[key] = deepmerge(target[key], source[key], optionsArgument)
|
33 | }
|
34 | })
|
35 | return destination
|
36 | }
|
37 |
|
38 | function deepmerge(target, source, optionsArgument) {
|
39 | var sourceIsArray = Array.isArray(source)
|
40 | var targetIsArray = Array.isArray(target)
|
41 | var options = optionsArgument || { arrayMerge: defaultArrayMerge }
|
42 | var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray
|
43 |
|
44 | if (!sourceAndTargetTypesMatch) {
|
45 | return cloneUnlessOtherwiseSpecified(source, optionsArgument)
|
46 | } else if (sourceIsArray) {
|
47 | var arrayMerge = options.arrayMerge || defaultArrayMerge
|
48 | return arrayMerge(target, source, optionsArgument)
|
49 | } else {
|
50 | return mergeObject(target, source, optionsArgument)
|
51 | }
|
52 | }
|
53 |
|
54 | deepmerge.all = function deepmergeAll(array, optionsArgument) {
|
55 | if (!Array.isArray(array)) {
|
56 | throw new Error('first argument should be an array')
|
57 | }
|
58 |
|
59 | return array.reduce(function(prev, next) {
|
60 | return deepmerge(prev, next, optionsArgument)
|
61 | }, {})
|
62 | }
|
63 |
|
64 | module.exports = deepmerge
|