wallet-core/node_modules/es5-ext/object/copy-deep.js

38 lines
935 B
JavaScript
Raw Normal View History

2017-08-14 05:01:11 +02:00
"use strict";
var forEach = require("./for-each")
, isPlainObject = require("./is-plain-object")
, ensureValue = require("./valid-value")
2017-12-10 21:51:33 +01:00
, isArray = Array.isArray;
2017-08-14 05:01:11 +02:00
2017-12-10 21:51:33 +01:00
var copyValue = function (value, ancestors, ancestorsCopy) {
var mode;
if (isPlainObject(value)) mode = "object";
else if (isArray(value)) mode = "array";
if (!mode) return value;
var copy = ancestorsCopy[ancestors.indexOf(value)];
if (copy) return copy;
copy = mode === "object" ? {} : [];
2017-08-14 05:01:11 +02:00
2017-12-10 21:51:33 +01:00
ancestors.push(value);
ancestorsCopy.push(copy);
if (mode === "object") {
forEach(value, function (item, key) {
copy[key] = copyValue(item, ancestors, ancestorsCopy);
});
2017-08-14 05:01:11 +02:00
} else {
2017-12-10 21:51:33 +01:00
value.forEach(function (item, index) {
copy[index] = copyValue(item, ancestors, ancestorsCopy);
});
2017-08-14 05:01:11 +02:00
}
2017-12-10 21:51:33 +01:00
ancestors.pop();
ancestorsCopy.pop();
return copy;
2017-08-14 05:01:11 +02:00
};
module.exports = function (source) {
2017-12-10 21:51:33 +01:00
return copyValue(ensureValue(source), [], []);
2017-08-14 05:01:11 +02:00
};