UNPKG

1.84 kBJavaScriptView Raw
1import {default as isObject} from "./isObject";
2
3/**
4 @function assign
5 @desc A deeply recursive version of `Object.assign`.
6 @param {...Object} objects
7 @example <caption>this</caption>
8assign({id: "foo", deep: {group: "A"}}, {id: "bar", deep: {value: 20}}));
9 @example <caption>returns this</caption>
10{id: "bar", deep: {group: "A", value: 20}}
11*/
12function assign() {
13 var objects = [], len = arguments.length;
14 while ( len-- ) objects[ len ] = arguments[ len ];
15
16
17 var target = objects[0];
18 var loop = function ( i ) {
19
20 var source = objects[i];
21
22 Object.keys(source).forEach(function (prop) {
23
24 var value = source[prop];
25
26 if (isObject(value)) {
27
28 if (target.hasOwnProperty(prop) && isObject(target[prop])) { target[prop] = assign({}, target[prop], value); }
29 else { target[prop] = value; }
30
31 }
32 else if (Array.isArray(value)) {
33
34 if (target.hasOwnProperty(prop) && Array.isArray(target[prop])) {
35
36 var targetArray = target[prop];
37
38 value.forEach(function (sourceItem, itemIndex) {
39
40 if (itemIndex < targetArray.length) {
41 var targetItem = targetArray[itemIndex];
42
43 if (Object.is(targetItem, sourceItem)) { return; }
44
45 if (isObject(targetItem) && isObject(sourceItem) || Array.isArray(targetItem) && Array.isArray(sourceItem)) {
46 targetArray[itemIndex] = assign({}, targetItem, sourceItem);
47 }
48 else { targetArray[itemIndex] = sourceItem; }
49
50 }
51 else { targetArray.push(sourceItem); }
52
53 });
54 }
55 else { target[prop] = value; }
56
57 }
58 else { target[prop] = value; }
59
60 });
61 };
62
63 for (var i = 1; i < objects.length; i++) loop( i );
64
65 return target;
66
67}
68
69export default assign;
70
71//# sourceMappingURL=assign.js.map
\No newline at end of file