UNPKG

1.85 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 if (target.hasOwnProperty(prop) && isObject(target[prop])) { target[prop] = assign({}, target[prop], value); }
28 else { target[prop] = assign({}, value); }
29 }
30 else if (Array.isArray(value)) {
31
32 if (target.hasOwnProperty(prop) && Array.isArray(target[prop])) {
33
34 var targetArray = target[prop];
35
36 value.forEach(function (sourceItem, itemIndex) {
37
38 if (itemIndex < targetArray.length) {
39 var targetItem = targetArray[itemIndex];
40
41 if (Object.is(targetItem, sourceItem)) { return; }
42
43 if (isObject(targetItem) && isObject(sourceItem) || Array.isArray(targetItem) && Array.isArray(sourceItem)) {
44 targetArray[itemIndex] = assign({}, targetItem, sourceItem);
45 }
46 else { targetArray[itemIndex] = sourceItem; }
47
48 }
49 else { targetArray.push(sourceItem); }
50
51 });
52 }
53 else { target[prop] = value; }
54
55 }
56 else { target[prop] = value; }
57
58 });
59 };
60
61 for (var i = 1; i < objects.length; i++) loop( i );
62
63 return target;
64
65}
66
67export default assign;
68
69//# sourceMappingURL=assign.js.map
\No newline at end of file