| |
| |
| |
| |
| |
| |
| |
| |
| import { isPlainObject, getObjectType, objectType } from "../modules/type"; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export const deepCopy = function (origin, map = new WeakMap()) { |
| |
| if (!origin || !isPlainObject(origin)) { |
| return origin; |
| } |
| |
| |
| const type = getObjectType(origin); |
| |
| |
| if (map.has(origin)) { |
| return map.get(origin); |
| } |
| |
| |
| |
| if (type === objectType.reg || type === objectType.date) { |
| const newObject = new origin.constructor(origin.valueOf()); |
| map.set(newObject); |
| return newObject; |
| } |
| |
| if (type === objectType.set) { |
| const newObject = new Set(); |
| for (const value of origin) { |
| newObject.add(deepCopy(value, map)); |
| } |
| map.set(newObject); |
| return newObject; |
| } |
| |
| if (type === objectType.map) { |
| const newObject = new Map(); |
| for (const [key, value] of origin) { |
| newObject.set(key, deepCopy(value, map)); |
| } |
| map.set(newObject); |
| return newObject; |
| } |
| |
| |
| |
| const keys = Reflect.ownKeys(origin); |
| |
| const descriptors = Object.getOwnPropertyDescriptors(origin); |
| |
| const newObject = Object.create(Object.getPrototypeOf(origin), descriptors); |
| |
| map.set(newObject); |
| keys.forEach((key) => { |
| const value = origin[key]; |
| newObject[key] = deepCopy(value, map); |
| }); |
| |
| |
| return type === objectType.array ? Array.from(newObject) : newObject; |
| }; |