mergeDeep.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.mergeDeep = void 0;
  4. const helpers_js_1 = require("./helpers.js");
  5. function mergeDeep(sources, respectPrototype = false) {
  6. const target = sources[0] || {};
  7. const output = {};
  8. if (respectPrototype) {
  9. Object.setPrototypeOf(output, Object.create(Object.getPrototypeOf(target)));
  10. }
  11. for (const source of sources) {
  12. if (isObject(target) && isObject(source)) {
  13. if (respectPrototype) {
  14. const outputPrototype = Object.getPrototypeOf(output);
  15. const sourcePrototype = Object.getPrototypeOf(source);
  16. if (sourcePrototype) {
  17. for (const key of Object.getOwnPropertyNames(sourcePrototype)) {
  18. const descriptor = Object.getOwnPropertyDescriptor(sourcePrototype, key);
  19. if ((0, helpers_js_1.isSome)(descriptor)) {
  20. Object.defineProperty(outputPrototype, key, descriptor);
  21. }
  22. }
  23. }
  24. }
  25. for (const key in source) {
  26. if (isObject(source[key])) {
  27. if (!(key in output)) {
  28. Object.assign(output, { [key]: source[key] });
  29. }
  30. else {
  31. output[key] = mergeDeep([output[key], source[key]], respectPrototype);
  32. }
  33. }
  34. else {
  35. Object.assign(output, { [key]: source[key] });
  36. }
  37. }
  38. }
  39. }
  40. return output;
  41. }
  42. exports.mergeDeep = mergeDeep;
  43. function isObject(item) {
  44. return item && typeof item === 'object' && !Array.isArray(item);
  45. }