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