d3plus-common
Version:
Common functions and methods used across D3plus modules.
69 lines (47 loc) • 1.85 kB
JavaScript
import {default as isObject} from "./isObject";
/**
@function assign
@desc A deeply recursive version of `Object.assign`.
@param {...Object} objects
@example <caption>this</caption>
assign({id: "foo", deep: {group: "A"}}, {id: "bar", deep: {value: 20}}));
@example <caption>returns this</caption>
{id: "bar", deep: {group: "A", value: 20}}
*/
function assign() {
var objects = [], len = arguments.length;
while ( len-- ) objects[ len ] = arguments[ len ];
var target = objects[0];
var loop = function ( i ) {
var source = objects[i];
Object.keys(source).forEach(function (prop) {
var value = source[prop];
if (isObject(value)) {
if (target.hasOwnProperty(prop) && isObject(target[prop])) { target[prop] = assign({}, target[prop], value); }
else { target[prop] = assign({}, value); }
}
else if (Array.isArray(value)) {
if (target.hasOwnProperty(prop) && Array.isArray(target[prop])) {
var targetArray = target[prop];
value.forEach(function (sourceItem, itemIndex) {
if (itemIndex < targetArray.length) {
var targetItem = targetArray[itemIndex];
if (Object.is(targetItem, sourceItem)) { return; }
if (isObject(targetItem) && isObject(sourceItem) || Array.isArray(targetItem) && Array.isArray(sourceItem)) {
targetArray[itemIndex] = assign({}, targetItem, sourceItem);
}
else { targetArray[itemIndex] = sourceItem; }
}
else { targetArray.push(sourceItem); }
});
}
else { target[prop] = value; }
}
else { target[prop] = value; }
});
};
for (var i = 1; i < objects.length; i++) loop( i );
return target;
}
export default assign;
//# sourceMappingURL=assign.js.map