js深拷贝 支持函数、Symbol、循环引用

/**
 * @description: 深拷贝
 * @param { any } source 数据源
 * @param { Map } cache 缓存(不传,有默认值)
 * @return { any } 复制值
 */
function deepCopy(source, cache = new Map()) {
  if (source instanceof Object) {
    // 函数
    if (typeof source === 'function') {
      return source;
    }

    // 数组
    if (Array.isArray(source)) {
      const arr = [];
      cache.set(source, arr);
      for (let i = 0; i < source.length; i++) {
        setValue(source, arr, i);
      }
      return arr;
    }

    // 对象
    const obj = {};
    cache.set(source, obj);
    for (const key in source) {
      if (Object.hasOwnProperty.call(source, key)) {
        setValue(source, obj, key);
      }
    }

    // Symbol
    const symbols = Object.getOwnPropertySymbols(source);
    for (const value of symbols) {
      setValue(source, obj, value);
    }
    return obj;
  }
  return source;

  // 设置值
  function setValue(source, target, key) {
    if (source[key] instanceof Object) {
      target[key] = cache.has(source[key]) ? cache.get(source[key]) : deepCopy(source[key], cache);
    } else {
      target[key] = source[key];
    }
  }
}
posted @   梦渊同学  阅读(288)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示