vlambda博客
学习文章列表

请分别用深度优先思想和广度优先思想实现一个拷贝函数?

//工具函数//重写 toString()和Object.prototype.toString()的不同,https://blog.csdn.net/shi_1204/article/details/79741220let getEmpty = function (origin) { if(Object.prototype.toString.call(origin) === '[object Object]'){ return {}; } if(Object.prototype.toString.call(origin) === '[object Array]'){ return []; }
return origin;};

//广度优先拷贝function deepCopyBFS(origin){ let queue = [];//用队列 先进先出 let map = new Map();//用于记录出现过的对象,用于处理环 let target = getEmpty(origin); if(target !== origin){ queue.push([origin,target]); map.set(origin,target); }
while (queue.length) { let [ori,tar] = queue.shift();//对象赋值,是指针引用 for(let key in ori){ if(map.get(ori[key])){//处理环状 tar[key] = map.get(tar[key]); continue; }
tar[key] = getEmpty(ori[key]); if(tar[key] !== ori[key]){ queue.push([ori[key],tar[key]]); map.set(ori[key],tar[key]); } } }
return target;}
//深度优先拷贝
function deepCopyDFS(origin){ let stack = [];//用堆 先进后出 let map = new Map();//用于记录出现过的对象,用于处理环 let target = getEmpty(origin); if(target !== origin){ stack.push([origin,target]); map.set(origin,target); }
while (stack.length) { let [ori,tar] = stack.pop();//对象赋值,是指针引用 for(let key in ori){ if(map.get(ori[key])){//处理环状 tar[key] = map.get(tar[key]); continue; }
tar[key] = getEmpty(ori[key]); if(tar[key] !== ori[key]){ stack.push([ori[key],tar[key]]); map.set(ori[key],tar[key]); } } }
return target;}
// test[deepCopyBFS, deepCopyDFS].forEach(deepCopy=>{ console.log(deepCopy({a:1})); console.log(deepCopy([1,2,{a:[3,4]}])) console.log(deepCopy(function(){return 1;})) console.log(deepCopy({ x:function(){ return "x"; }, val:3, arr: [ 1, {test:1} ] }))
let circle = {}; circle.child = circle; console.log(deepCopy(circle));})