Breadth-first traversal and depth-first traversal applications – implement deep copies of objects

// To determine the type of object to be copied, consider only two complex data types, object and array
function getEmpty(obj) {
    if (Object.prototype.toString.call(obj) === '[object Object]') {
        return {};
    } else if (Object.prototype.toString.call(obj) === '[object Array]') {
        return [];
    }
    return obj; // Basic data type processing
}
// width first traversal
function bfsCopy(origin) {
    let queue = [];
    let map = new Map(a);// Record the occurrence of the object, used to process the ring
    let ans = getEmpty(origin);
    if(ans ! == origin) { queue.push([origin, ans]); map.set(origin, ans); }while (queue.length) {
        let [ori, ans] = queue.shift();
        for (let key in ori) {
            if (map.get(ori[key])) { // Indicates that the key value has already been set, so there is no need to perform recursive operations on the inside of the key, otherwise it will fall into an infinite loop
                ans[key] = map.get(ori[key]);
                continue;
            }
            ans[key] = getEmpty(ori[key]);
            if(ans[key] ! == ori[key]) { queue.push(ori[key]); map.set(ori[key], ans[key]); }}}return ans;
}
// Depth-first traversal, recursive
dfsCopy1.prototype.map = new Map(a);// Store the variable map in the prototype so that the map can be accessed at each level of recursive calls
function dfsCopy1(origin) {
    let ans = getEmpty(origin);
    dfsCopy1.prototype.map.set(origin, ans);
    if (ans === origin) {
        return ans;
    }
    for (let key in origin) {
        if (dfsCopy1.prototype.map.get(origin[key])) { / / loop processing
            ans[key] = dfsCopy1.prototype.map.get(origin[key]);
            continue;
        }
        ans[key] = dfsCopy1(origin[key]);
    }
    return ans;
}
// Depth-first traversal is non-recursive
function dfsCopy2(origin) {
    let stack = [];
    let map = new Map(a);let ans = getEmpty(origin);
    if (ans === origin) return ans;
    stack.push([origin, ans]);
    while (stack.length) {
        let [childori, childans] = stack.pop();
        for (let key in childori) {
            if (map.get(childori[key])) { / / loop processing
                childans[key] = childori[key];
                continue;
            }
            childans[key] = getEmpty(childori[key]);
            if(childans[key] ! == childori[key]) { stack.push([childori[key], childans[key]]); map.set(childori[key], childans[key]); }}}return ans;
}
let obj = {
    a: 2.b: {
        c: 3
    }
}
obj.b.d = obj;

console.log(bfsCopy(obj.b.d.a)); / / 2
Copy the code