DEV Community

Cover image for Deepclone polyfill javascript
chandra penugonda
chandra penugonda

Posted on • Edited on

Deepclone polyfill javascript

Write polyfill for deepclone

const obj = { a: 1, b: [2, 3, { c: 4}]};
const clonedObj = deepClone(obj);
// clonedObj is a deep clone of obj
Enter fullscreen mode Exit fullscreen mode
function deepClone(obj) {
  if (typeof obj !== "object" || obj === null) {
    return obj;
  }

  let result;
  if (obj instanceof Date) {
    return new Date(obj);
  }
  if (Array.isArray(obj)) {
    result = [];
    for (let i = 0; i < obj.length; i++) {
      result.push(deepClone(obj[i]));
    }
  } else {
    result = {};
    for (const i in obj) {
      result[i] = deepClone(obj[i]);
    }
  }

  return result;
}

Enter fullscreen mode Exit fullscreen mode

Explanation

  • This function recursively clones objects and arrays. It works as follows:
  • It checks if the input is a primitive value or null, and if so just returns the value.
  • For arrays:
  • It creates an empty array.
  • It loops through the input array and calls deepClone() on each element, adding the result to the new array.
  • For objects:
  • It creates an empty object.
  • It loops through the object's properties and calls deepClone() on each property value, assigning the result to the new object.
  • It returns the cloned result.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay