copy-deep.js 934 B

1234567891011121314151617181920212223242526272829303132333435
  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. var copyValue = function (value, ancestors, ancestorsCopy) {
  7. var mode;
  8. if (isPlainObject(value)) mode = "object";
  9. else if (isArray(value)) mode = "array";
  10. if (!mode) return value;
  11. var copy = ancestorsCopy[ancestors.indexOf(value)];
  12. if (copy) return copy;
  13. copy = mode === "object" ? {} : [];
  14. ancestors.push(value);
  15. ancestorsCopy.push(copy);
  16. if (mode === "object") {
  17. forEach(value, function (item, key) {
  18. copy[key] = copyValue(item, ancestors, ancestorsCopy);
  19. });
  20. } else {
  21. value.forEach(function (item, index) {
  22. copy[index] = copyValue(item, ancestors, ancestorsCopy);
  23. });
  24. }
  25. ancestors.pop();
  26. ancestorsCopy.pop();
  27. return copy;
  28. };
  29. module.exports = function (source) { return copyValue(ensureValue(source), [], []); };