Skip to content
Snippets Groups Projects
Commit eae2402c authored by Sebastian Listl's avatar Sebastian Listl :speech_balloon:
Browse files

Util_lib Utils.clone improved

parent fa52aec2
No related branches found
No related tags found
No related merge requests found
......@@ -61,29 +61,46 @@ Utils.isNullOrEmpty = function (pObject)
*
* var original = new MyObject();
* original.name = "Jotaro";
* original.obj1 = {};
* original.obj2 = original.obj1;
*
* var copy = ObjectUtils.clone(original);
* copy.name = "Josuke";
*
* logging.log(original.name != copy.name); //true
* logging.log(copy instanceof MyObject()); //true (prototypes are set correctly)
* logging.log(copy instanceof MyObject()); //true, prototypes are set correctly
* logging.log(copy.obj1 === copy.obj2); //true, relative object references are kept
*/
Utils.clone = function (pObject)
{
if (!Utils.isObject(pObject) || pObject === null)
return pObject; //Return the value if inObject is not an object
var referenceMap = new Map();
return _clone(pObject);
var clonedObject = Array.isArray(pObject)
? []
: Object.create(Object.getPrototypeOf(pObject)); //set the prototype of the given object
for (let key in pObject)
function _clone (pObject)
{
var value = pObject[key];
clonedObject[key] = Utils.clone(value); //Recursively (deep) copy for nested objects, including arrays
if (typeof pObject !== "object" || pObject === null)
return pObject; //Return the value if inObject is not an object
if (referenceMap.has(pObject))
return referenceMap.get(pObject);
var clonedObject = Array.isArray(pObject)
? []
: Object.create(Object.getPrototypeOf(pObject)); //set the prototype of the given object
/* keeps track of all encountered objects and maps the original to the copy, this makes it possible to:
- have the same relative references in the copy as in the original
- copy cyclic references without error */
referenceMap.set(pObject, clonedObject);
for (let key in pObject)
{
var value = pObject[key];
clonedObject[key] = _clone(value); //Recursively (deep) copy for nested objects, including arrays
}
return clonedObject;
}
return clonedObject;
}
/**
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment