cloneDeep.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var baseClone = require('../internal/baseClone'),
  2. bindCallback = require('../internal/bindCallback');
  3. /**
  4. * Creates a deep clone of `value`. If `customizer` is provided it's invoked
  5. * to produce the cloned values. If `customizer` returns `undefined` cloning
  6. * is handled by the method instead. The `customizer` is bound to `thisArg`
  7. * and invoked with up to three argument; (value [, index|key, object]).
  8. *
  9. * **Note:** This method is loosely based on the
  10. * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
  11. * The enumerable properties of `arguments` objects and objects created by
  12. * constructors other than `Object` are cloned to plain `Object` objects. An
  13. * empty object is returned for uncloneable values such as functions, DOM nodes,
  14. * Maps, Sets, and WeakMaps.
  15. *
  16. * @static
  17. * @memberOf _
  18. * @category Lang
  19. * @param {*} value The value to deep clone.
  20. * @param {Function} [customizer] The function to customize cloning values.
  21. * @param {*} [thisArg] The `this` binding of `customizer`.
  22. * @returns {*} Returns the deep cloned value.
  23. * @example
  24. *
  25. * var users = [
  26. * { 'user': 'barney' },
  27. * { 'user': 'fred' }
  28. * ];
  29. *
  30. * var deep = _.cloneDeep(users);
  31. * deep[0] === users[0];
  32. * // => false
  33. *
  34. * // using a customizer callback
  35. * var el = _.cloneDeep(document.body, function(value) {
  36. * if (_.isElement(value)) {
  37. * return value.cloneNode(true);
  38. * }
  39. * });
  40. *
  41. * el === document.body
  42. * // => false
  43. * el.nodeName
  44. * // => BODY
  45. * el.childNodes.length;
  46. * // => 20
  47. */
  48. function cloneDeep(value, customizer, thisArg) {
  49. return typeof customizer == 'function'
  50. ? baseClone(value, true, bindCallback(customizer, thisArg, 3))
  51. : baseClone(value, true);
  52. }
  53. module.exports = cloneDeep;