mergeDeep.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var tslib_1 = require("tslib");
  4. var hasOwnProperty = Object.prototype.hasOwnProperty;
  5. function mergeDeep() {
  6. var sources = [];
  7. for (var _i = 0; _i < arguments.length; _i++) {
  8. sources[_i] = arguments[_i];
  9. }
  10. return mergeDeepArray(sources);
  11. }
  12. exports.mergeDeep = mergeDeep;
  13. function mergeDeepArray(sources) {
  14. var target = sources[0] || {};
  15. var count = sources.length;
  16. if (count > 1) {
  17. var pastCopies = [];
  18. target = shallowCopyForMerge(target, pastCopies);
  19. for (var i = 1; i < count; ++i) {
  20. target = mergeHelper(target, sources[i], pastCopies);
  21. }
  22. }
  23. return target;
  24. }
  25. exports.mergeDeepArray = mergeDeepArray;
  26. function isObject(obj) {
  27. return obj !== null && typeof obj === 'object';
  28. }
  29. function mergeHelper(target, source, pastCopies) {
  30. if (isObject(source) && isObject(target)) {
  31. if (Object.isExtensible && !Object.isExtensible(target)) {
  32. target = shallowCopyForMerge(target, pastCopies);
  33. }
  34. Object.keys(source).forEach(function (sourceKey) {
  35. var sourceValue = source[sourceKey];
  36. if (hasOwnProperty.call(target, sourceKey)) {
  37. var targetValue = target[sourceKey];
  38. if (sourceValue !== targetValue) {
  39. target[sourceKey] = mergeHelper(shallowCopyForMerge(targetValue, pastCopies), sourceValue, pastCopies);
  40. }
  41. }
  42. else {
  43. target[sourceKey] = sourceValue;
  44. }
  45. });
  46. return target;
  47. }
  48. return source;
  49. }
  50. function shallowCopyForMerge(value, pastCopies) {
  51. if (value !== null &&
  52. typeof value === 'object' &&
  53. pastCopies.indexOf(value) < 0) {
  54. if (Array.isArray(value)) {
  55. value = value.slice(0);
  56. }
  57. else {
  58. value = tslib_1.__assign({ __proto__: Object.getPrototypeOf(value) }, value);
  59. }
  60. pastCopies.push(value);
  61. }
  62. return value;
  63. }
  64. //# sourceMappingURL=mergeDeep.js.map