copy-deep.js 963 B

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