deepClone.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var clone = require('./clone');
  2. var forOwn = require('../object/forOwn');
  3. var kindOf = require('./kindOf');
  4. var isPlainObject = require('./isPlainObject');
  5. /**
  6. * Recursively clone native types.
  7. */
  8. function deepClone(val, instanceClone) {
  9. switch ( kindOf(val) ) {
  10. case 'Object':
  11. return cloneObject(val, instanceClone);
  12. case 'Array':
  13. return cloneArray(val, instanceClone);
  14. default:
  15. return clone(val);
  16. }
  17. }
  18. function cloneObject(source, instanceClone) {
  19. if (isPlainObject(source)) {
  20. var out = {};
  21. forOwn(source, function(val, key) {
  22. this[key] = deepClone(val, instanceClone);
  23. }, out);
  24. return out;
  25. } else if (instanceClone) {
  26. return instanceClone(source);
  27. } else {
  28. return source;
  29. }
  30. }
  31. function cloneArray(arr, instanceClone) {
  32. var out = [],
  33. i = -1,
  34. n = arr.length,
  35. val;
  36. while (++i < n) {
  37. out[i] = deepClone(arr[i], instanceClone);
  38. }
  39. return out;
  40. }
  41. module.exports = deepClone;