Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

深拷贝deepClone #2

Open
Chersquwn opened this issue Apr 9, 2020 · 0 comments
Open

深拷贝deepClone #2

Chersquwn opened this issue Apr 9, 2020 · 0 comments

Comments

@Chersquwn
Copy link
Owner

Chersquwn commented Apr 9, 2020

能处理循环引用的深拷贝

通过哈希表保存已经拷贝过的对象,再次遇到相同对象属性时,直接从哈希表中取出,避免出现死循环。

/**
 * 深拷贝
 *
 * @export
 * @param {*} source
 * @param {*} [hash=new WeakMap()]
 * @returns
 */
export function deepClone(source: any, hash = new WeakMap()) {
  // 非 object 对象直接原值返回
  if (typeof source !== 'object' || source === null) {
    return source
  }

  // 从 hash 表中查找对象是否已经拷贝过
  // 如果已经拷贝过,直接取出该值返回
  if (hash.has(source)) return hash.get(source)

  // 分别处理 array 和 object
  const target: any = Array.isArray(source) ? [] : {}

  // 将 source 遍历后生成的 target 保存进 hash 表
  hash.set(source, target)

  // 遍历 source 对象的属性
  Reflect.ownKeys(source).forEach(key => {
    if (typeof source === 'object' && source !== null) {
      // 如果是 object 类型,递归调用 deepClone
      target[key] = deepClone(source[key], hash)
    } else {
      // 非 object 类型原值赋值
      target[key] = source[key]
    }
  })

  return target
}
@Chersquwn Chersquwn changed the title 深拷贝 深拷贝deepClone Apr 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant