-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.js
63 lines (51 loc) · 1.32 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*!
* merge-deep <https://github.com/jonschlinkert/merge-deep>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var union = require('arr-union');
var clone = require('clone-deep');
var typeOf = require('kind-of');
module.exports = function mergeDeep(orig, objects) {
if (!isObject(orig) && !Array.isArray(orig)) {
orig = {};
}
var target = clone(orig);
var len = arguments.length;
var idx = 0;
while (++idx < len) {
var val = arguments[idx];
if (isObject(val) || Array.isArray(val)) {
merge(target, val);
}
}
return target;
};
function merge(target, obj) {
for (var key in obj) {
if (!isValidKey(key) || !hasOwn(obj, key)) {
continue;
}
var oldVal = obj[key];
var newVal = target[key];
if (isObject(newVal) && isObject(oldVal)) {
target[key] = merge(newVal, oldVal);
} else if (Array.isArray(newVal)) {
target[key] = union([], newVal, oldVal);
} else {
target[key] = clone(oldVal);
}
}
return target;
}
function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function isObject(val) {
return typeOf(val) === 'object' || typeOf(val) === 'function';
}
function isValidKey(key) {
return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
}