UNPKG

1.19 kBJavaScriptView Raw
1var clone = require('./clone');
2
3module.exports = merge;
4
5function typesMatch(a, b) {
6 return (typeof a === typeof b) && (Array.isArray(a) === Array.isArray(b));
7}
8
9/**
10 * A deep merge of the source based on the target.
11 * @param {Object} source [description]
12 * @param {Object} target [description]
13 * @return {Object} [description]
14 */
15function merge(source, target, result) {
16 if (result === undefined) {
17 result = clone(source);
18 }
19
20 // merge missing values from the target to the source
21 Object.getOwnPropertyNames(target).forEach(function (key) {
22 if (source[key] === undefined) {
23 result[key] = target[key];
24 }
25 });
26
27 Object.getOwnPropertyNames(source).forEach(function (key) {
28 var value = source[key];
29
30 if (target[key] && typesMatch(value, target[key])) {
31 // merge empty values
32 if (value === '') {
33 result[key] = target[key];
34 }
35
36 if (Array.isArray(value)) {
37 if (value.length === 0 && target[key].length) {
38 result[key] = target[key].slice(0);
39 }
40 } else if (typeof value === 'object') {
41 result[key] = merge(value, target[key]);
42 }
43 }
44 });
45
46 return result;
47}
\No newline at end of file