deepcopy.js
deepcopysafe.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Precondition: 1. "obj is not allowed to contain references pointing to itself" | |
// (function calls itself recursively, so this precondition | |
// must be matched by all contained objects) | |
// | |
functiondeepCopy(obj) | |
{ | |
if(typeofobj!=='object'||obj===null) | |
returnobj | |
constnewObject=(obj.constructor===Array ? [] : {}) | |
constkeys=Object.keys(obj) | |
for(constiinkeys){ | |
newObject[keys[i]]=deepCopy(obj[keys[i]]) | |
} | |
returnnewObject | |
} | |
consto1={ | |
a: null, | |
b: 1, | |
c: 'string', | |
d: [1,2,3,{4: null}], | |
e: { | |
shared_value: 'deep copy', | |
}, | |
} | |
// test shallow vs. deep copy | |
consto1_shallow_copy=Object.assign({},o1) | |
consto1_deep_copy=deepCopy(o1) | |
o1.e.shared_value='shallow copy' | |
console.log("o1_shallow_copy: ",o1_shallow_copy) | |
console.log("o1_deep_copy: ",o1_deep_copy) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Supports objects with self references | |
// | |
functiondeepCopy(obj) | |
{ | |
constself_refs=newMap() | |
functiondeepCopySafe(obj) | |
{ | |
if(typeofobj!=='object'||obj===null) | |
returnobj | |
if(self_refs.has(obj)) | |
returnself_refs.get(obj) | |
constnewObject=(obj.constructor===Array ? [] : {}) | |
self_refs.set(obj,newObject) | |
constkeys=Object.keys(obj) | |
for(constiinkeys){ | |
newObject[keys[i]]=deepCopySafe(obj[keys[i]]) | |
} | |
returnnewObject | |
} | |
returndeepCopySafe(obj) | |
} | |
// test circular linked list | |
consto2={ | |
value: 2, | |
next: null, | |
} | |
consto3={ | |
value: 3, | |
next: o2, | |
} | |
o2.next=o3 | |
consto4=deepCopy(o2) | |
console.log("linked list:",o2) | |
console.log("deep copy of linked list:",o4) |