Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. /**
  2. * Returns a deep copy of the array or object passed to it.
  3. * Useful for copying objects and arrays with nested complex types.
  4. *
  5. * @param {array|object} o The value to deep copy, could be array or object.
  6. * @returns {array|object} Returns a deep copy of the supplied array or object.
  7. */
  8. function deepClone(o) {
  9. // Construct the copy `output` array or object.
  10. // Use `Array.isArray()` to check if `o` is an array.
  11. // If `o` is an array, set the copy `output` to an empty array (`[]`).
  12. // Otherwise, set the copy `output` to an empty object (`{}`).
  13. //
  14. // If `Array.isArray()` is not supported, this can be used as an alternative:
  15. // Object.prototype.toString.call(o) === '[object Array]'
  16. // However, it is a fragile alternative.
  17. const output = Array.isArray(o) ? [] : {};
  18.  
  19. // Loop through all the properties of `o`
  20. for (let i in o) {
  21. // Get the value of the current property of `o`
  22. const value = o[i];
  23.  
  24. // If the value of the current property is an object and is not null,
  25. // deep clone the value and assign it to the same property on the copy `output`.
  26. // Otherwise, assign the raw value to the property on the copy `output`.
  27. output[i] = value !== null && typeof value === 'object' ? deepClone(value) : value;
  28. }
  29.  
  30. // Return the copy `output`.
  31. return output;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement