DEV Community

Cover image for Deepclone polyfill javascript
chandra penugonda
chandra penugonda

Posted on • Updated 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.

Top comments (0)