Skip to content

Commit

Permalink
feat: Object.assignDeep
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Oct 13, 2017
1 parent 7e14ffd commit 2345e0b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
33 changes: 33 additions & 0 deletions object/assign-deep.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use strict";

var includes = require("../array/#/contains")
, uniq = require("../array/#/uniq")
, objForEach = require("./for-each")
, isPlainObject = require("./is-plain-object")
, ensureObject = require("./valid-object");

var isArray = Array.isArray, slice = Array.prototype.slice;

var deepAssign = function (source, target) {
if (isPlainObject(source)) {
if (!isPlainObject(target)) return target;
objForEach(target, function (value, key) {
source[key] = deepAssign(source[key], value);
});
return source;
}
if (isArray(source)) {
if (!isArray(target)) return target;
target.forEach(function (item) {
if (!includes.call(source, item)) source.push(item);
});
return source;
}
return target;
};

module.exports = function (target /*, ...objects*/) {
return uniq
.call([ensureObject(target)].concat(slice.call(arguments, 1).map(ensureObject)))
.reduce(deepAssign);
};
1 change: 1 addition & 0 deletions object/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

module.exports = {
assign: require("./assign"),
assignDeep: require("./assign-deep"),
clear: require("./clear"),
compact: require("./compact"),
compare: require("./compare"),
Expand Down
14 changes: 14 additions & 0 deletions test/object/assign-deep.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"use strict";

module.exports = function (t, a) {
var o1 = { a: 1, b: 2 }, o2 = { b: 3, c: 4 };

a(t(o1, o2), o1, "Returns self");
a.deep(o1, { a: 1, b: 3, c: 4 }, "Single: content");

a.deep(t({}, o1, o2), { a: 1, b: 3, c: 4 }, "Multi argument");

var obj1 = { foo: { bar: 3, marko: true } }
, obj2 = { foo: { elo: 12, marko: false }, miszka: [23] };
a.deep(t({}, obj1, obj2), { foo: { bar: 3, marko: false, elo: 12 }, miszka: [23] });
};

0 comments on commit 2345e0b

Please # to comment.