index.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // @ts-nocheck
  2. /**
  3. * 深拷贝
  4. * @returns
  5. */
  6. export function cloneDeep<T>(obj : any) : T {
  7. if (obj === null) {
  8. return null as unknown as T;
  9. }
  10. if (obj instanceof Set) {
  11. return new Set([...obj]) as unknown as T;
  12. }
  13. if (obj instanceof Map) {
  14. return new Map([...obj]) as unknown as T;
  15. }
  16. if (obj instanceof WeakMap) {
  17. let weakMap = new WeakMap();
  18. weakMap = obj;
  19. return weakMap as unknown as T;
  20. }
  21. if (obj instanceof WeakSet) {
  22. let weakSet = new WeakSet();
  23. weakSet = obj;
  24. return weakSet as unknown as T;
  25. }
  26. if (obj instanceof RegExp) {
  27. return new RegExp(obj) as unknown as T;
  28. }
  29. if (typeof obj === 'undefined') {
  30. return undefined as unknown as T;
  31. }
  32. if (Array.isArray(obj)) {
  33. return obj.map(cloneDeep) as unknown as T;
  34. }
  35. if (obj instanceof Date) {
  36. return new Date(obj.getTime()) as unknown as T;
  37. }
  38. if (typeof obj !== 'object') {
  39. return obj;
  40. }
  41. const newObj : any = {};
  42. for (const [key, value] of Object.entries(obj)) {
  43. newObj[key] = cloneDeep(value);
  44. }
  45. const symbolkeys = Object.getOwnPropertySymbols(obj);
  46. for (const key of symbolkeys) {
  47. newObj[key] = cloneDeep(obj[key]);
  48. }
  49. return newObj;
  50. }