Skip to content
js
function deepCopy(obj) {
  // 处理特殊对象类型
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  // 处理 Date、RegExp、Function 等特殊对象类型
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }

  if (obj instanceof RegExp) {
    return new RegExp(obj);
  }

  if (obj instanceof Function) {
    return new Function('return ' + obj.toString())();
  }

  // 处理数组类型
  if (obj instanceof Array) {
    return obj.map(deepCopy);
  }

  // 处理 Map 类型
  if (obj instanceof Map) {
    const result = new Map();
    obj.forEach((value, key) => {
      result.set(key, deepCopy(value));
    });
    return result;
  }

  // 处理 Set 类型
  if (obj instanceof Set) {
    const result = new Set();
    obj.forEach(value => {
      result.add(deepCopy(value));
    });
    return result;
  }

  // 处理普通对象类型
  const result = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = deepCopy(obj[key]);
    }
  }
  return result;
}