DEV Community

Discussion on: Making a basic deepCopy function in JS

Collapse
 
govvj profile image
Govind Vijay

Your logic has a bug.
let a = {}; a.b = {}; a.b.c = a; // circular dependency
a.x = 'x'; // to track if deepclone is working or not
let a_cl = deepCopy(a);
a_cl.x = 'xx';
console.log(a_cl.b.c.x)
Above line print 'x' which is wrong. It should print 'xx';
This value is coming from "a" instead it should be coming from "a_cl".

When you do "return obj;" it does not clone the cycle and istead uses the original cycle.

Collapse
 
lakbychance profile image
Lakshya Thakur

Thank you for pointing that out 😁. I am thinking of fixing it by using WeakMap to store corresponding newObj for obj and returning the newObj when same obj occurs. I think that should work.