欢迎代码找茬-小弟初来乍到

287 阅读1分钟

深克隆 小弟已做事6年之久,平日里只管敲敲代码,写写bug,最近流行卷,小弟深感家庭责任重大,不可拘泥于工作中无法自拔,遂决定开始写文章,提升勉励自己,持续学习。不可作废光阴。 先来看看小弟写的深克隆,有问题还请评论区指证

const _completeDeepClone = (target, map = new Map()) => {
  if (target == null) {
    return null
  }
  // 补全代码
  if (typeof target != 'object') return target
  console.info(target.constructor)

  let newObj = new target.constructor()
  if (map.has(target)) {
    return map.get(target)
  } else {
    map.set(target, newObj)
  }
  switch (target.constructor.name) {
    case 'Set':
      target.forEach((item) => {
        newObj.add(_completeDeepClone(item, map))
      })
      return newObj
    case 'Map':
      target.forEach((item, key) => {
        newObj.set(key, _completeDeepClone(item, map))
      })
      return newObj
    case 'Boolean':
    case 'Error':
    case 'Date':
    case 'String':
    case 'Number':
      return new target.constructor(target)
    case 'Symbol':
      return Symbol(targe.description)
    case 'Function':
      return new Function('return' + target.toString())
    case 'RegExp':
      return new RegExp(target)
  }
  console.info('执行了没有')
  for (let key in target) {
    console.info('执行了没有', key)
    newObj[key] = _completeDeepClone(target[key], map)
  }
  return newObj
}
// 然后是测试代码
const o1 = {
  name: 'g',
  age: 18,
  o: { name: 'o' },
  a: [1, 2],
  r: new RegExp(),
  d: new Date(),
  f: function (){
      return "有bug没"
  }
}
o1.self = o1
const o2 = _completeDeepClone(o1)
o1.name = 'z'
o1.age = 1
o1.d = new Date().getTime()
o1.r=new RegExp("/\d/")
o1.f = function (){
     return " 我觉得没啥bug"
}
const judge = o1.name !== o2.name

console.info(o1, o2,o1.f.toString(),o2.f.toString())

打印结果

[Function: Object]
执行了没有
执行了没有 name
执行了没有 age
执行了没有 o
[Function: Object]
执行了没有
执行了没有 name
执行了没有 a
[Function: Array]
执行了没有
执行了没有 0
执行了没有 1
执行了没有 r
[Function: RegExp]
执行了没有 d
[Function: Date]
执行了没有 f
执行了没有 self
[Function: Object]
{ name: 'z',
  age: 1,
  o: { name: 'o' },
  a: [ 1, 2 ],
  r: /\/d\//,
  d: 1648214858911,
  f: [Function],
  self: [Circular] } { name: 'g',
  age: 18,
  o: { name: 'o' },
  a: [ 1, 2 ],
  r: /(?:)/,
  d: 2022-03-25T13:27:38.907Z,
  f: [Function: f],
  self: [Circular] }
  'function (){\n     return " 我觉得没啥bug"\n}' 'function ()
  {\n      return "有bug没"\n  }'

完事,没写过文章,得练,慢慢来不着急