Advertisement
bebo231312312321

Untitled

Feb 5th, 2024
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function deepCopy(obj, hash = new WeakMap()) {
  2.   if (obj === null) return null;
  3.   if (typeof obj !== 'object') return obj;
  4.   if (obj instanceof Date) return new Date(obj);
  5.   if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
  6.   if (hash.has(obj)) return hash.get(obj);
  7.  
  8.   const result = Array.isArray(obj) ? [] : {};
  9.   hash.set(obj, result);
  10.  
  11.   Object.keys(obj).forEach(key => {
  12.     if (typeof obj[key] === 'object' && obj[key] !== null) {
  13.       result[key] = deepCopy(obj[key], hash);
  14.     } else {
  15.       result[key] = obj[key];
  16.     }
  17.   });
  18.  
  19.   return result;
  20. }
  21.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement