assign-deep.js 926 B

123456789101112131415161718192021222324252627282930313233
  1. "use strict";
  2. var includes = require("../array/#/contains")
  3. , uniq = require("../array/#/uniq")
  4. , objForEach = require("./for-each")
  5. , isPlainObject = require("./is-plain-object")
  6. , ensureValue = require("./valid-value");
  7. var isArray = Array.isArray, slice = Array.prototype.slice;
  8. var deepAssign = function (target, source) {
  9. if (isPlainObject(target)) {
  10. if (!isPlainObject(source)) return source;
  11. objForEach(source, function (value, key) {
  12. target[key] = deepAssign(target[key], value);
  13. });
  14. return target;
  15. }
  16. if (isArray(target)) {
  17. if (!isArray(source)) return source;
  18. source.forEach(function (item) {
  19. if (!includes.call(target, item)) target.push(item);
  20. });
  21. return target;
  22. }
  23. return source;
  24. };
  25. module.exports = function (target /*, ...objects*/) {
  26. return uniq
  27. .call([ensureValue(target)].concat(slice.call(arguments, 1).map(ensureValue)))
  28. .reduce(deepAssign);
  29. };