clone.js 793 B

1234567891011121314151617181920212223242526272829303132
  1. import defaultValue from "./defaultValue.js";
  2. /**
  3. * Clones an object, returning a new object containing the same properties.
  4. *
  5. * @function
  6. *
  7. * @param {Object} object The object to clone.
  8. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  9. * @returns {Object} The cloned object.
  10. */
  11. function clone(object, deep) {
  12. if (object === null || typeof object !== "object") {
  13. return object;
  14. }
  15. deep = defaultValue(deep, false);
  16. const result = new object.constructor();
  17. for (const propertyName in object) {
  18. if (object.hasOwnProperty(propertyName)) {
  19. let value = object[propertyName];
  20. if (deep) {
  21. value = clone(value, deep);
  22. }
  23. result[propertyName] = value;
  24. }
  25. }
  26. return result;
  27. }
  28. export default clone;