All Interview Questions
About Lesson
//**** Deep copy using Stringify ****//
// Issue using Stringify for Deep Copy It is not supporting following
// function, Infinity, NaN, circular references
// Map, Set, Date, RegExp
// const obj = {“name”:”sanjay”} -> Json

const original = {a:1,b:{c:2}};
function deepcopy(obj){
    return JSON.parse(JSON.stringify(obj));
}

const copy = deepcopy(original);
//**** Deep copy using lodash function ****//
const _ = require(‘lodash’);

const original = {a:1,b:{c:2}};
const copy = _.cloneDeep(original);

const original = {a:1,b:{c:2}};
const copy = structuredClone(original);
console.log(copy)
// Custom Polyfill for Deep Copy
if(!Object.deepCopy){
    Object.deepCopy = function(val){
        if(val === null || typeof val !== “object”){
            return val;
        }
       
        if(Array.isArray(val)){
            return val.map(item => Object.deepCopy(item));
        }
       
        return Object.keys(val).reduce((acc,key)=>{
            acc[key] = Object.deepCopy(val[key]);
            return acc;
        }, {})
    }
}

const original = {a:1,b:{c:2}};
const copy = Object.deepCopy(original);
console.log(“original”, original);
copy.b = “Sanjay”;
console.log(“copy”, copy);

© GeekySanjay