combine.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import defaultValue from "./defaultValue.js";
  2. import defined from "./defined.js";
  3. /**
  4. * Merges two objects, copying their properties onto a new combined object. When two objects have the same
  5. * property, the value of the property on the first object is used. If either object is undefined,
  6. * it will be treated as an empty object.
  7. *
  8. * @example
  9. * const object1 = {
  10. * propOne : 1,
  11. * propTwo : {
  12. * value1 : 10
  13. * }
  14. * }
  15. * const object2 = {
  16. * propTwo : 2
  17. * }
  18. * const final = Cesium.combine(object1, object2);
  19. *
  20. * // final === {
  21. * // propOne : 1,
  22. * // propTwo : {
  23. * // value1 : 10
  24. * // }
  25. * // }
  26. *
  27. * @param {Object} [object1] The first object to merge.
  28. * @param {Object} [object2] The second object to merge.
  29. * @param {Boolean} [deep=false] Perform a recursive merge.
  30. * @returns {Object} The combined object containing all properties from both objects.
  31. *
  32. * @function
  33. */
  34. function combine(object1, object2, deep) {
  35. deep = defaultValue(deep, false);
  36. const result = {};
  37. const object1Defined = defined(object1);
  38. const object2Defined = defined(object2);
  39. let property;
  40. let object1Value;
  41. let object2Value;
  42. if (object1Defined) {
  43. for (property in object1) {
  44. if (object1.hasOwnProperty(property)) {
  45. object1Value = object1[property];
  46. if (
  47. object2Defined &&
  48. deep &&
  49. typeof object1Value === "object" &&
  50. object2.hasOwnProperty(property)
  51. ) {
  52. object2Value = object2[property];
  53. if (typeof object2Value === "object") {
  54. result[property] = combine(object1Value, object2Value, deep);
  55. } else {
  56. result[property] = object1Value;
  57. }
  58. } else {
  59. result[property] = object1Value;
  60. }
  61. }
  62. }
  63. }
  64. if (object2Defined) {
  65. for (property in object2) {
  66. if (
  67. object2.hasOwnProperty(property) &&
  68. !result.hasOwnProperty(property)
  69. ) {
  70. object2Value = object2[property];
  71. result[property] = object2Value;
  72. }
  73. }
  74. }
  75. return result;
  76. }
  77. export default combine;