copy-deep.js 939 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. var forEach = require('./for-each')
  3. , isPlainObject = require('./is-plain-object')
  4. , value = require('./valid-value')
  5. , isArray = Array.isArray
  6. , copy, copyItem;
  7. copyItem = function (value, key) {
  8. var index;
  9. if (!isPlainObject(value) && !isArray(value)) return value;
  10. index = this[0].indexOf(value);
  11. if (index === -1) return copy.call(this, value);
  12. return this[1][index];
  13. };
  14. copy = function (source) {
  15. var target = isArray(source) ? [] : {};
  16. this[0].push(source);
  17. this[1].push(target);
  18. if (isArray(source)) {
  19. source.forEach(function (value, key) {
  20. target[key] = copyItem.call(this, value, key);
  21. }, this);
  22. } else {
  23. forEach(source, function (value, key) {
  24. target[key] = copyItem.call(this, value, key);
  25. }, this);
  26. }
  27. return target;
  28. };
  29. module.exports = function (source) {
  30. var obj = Object(value(source));
  31. if (obj !== source) return obj;
  32. return copy.call([[], []], obj);
  33. };