Skip to content

Latest commit

 

History

History
43 lines (38 loc) · 1.51 KB

deepClone.md

File metadata and controls

43 lines (38 loc) · 1.51 KB
title tags author_title author_url author_image_url description image
deepClone
object,recursion,intermediate
Deepak Vishwakarma
Implementation of "deepClone" in typescript, javascript and deno.

TS JS Deno

Creates a deep clone of an object.

Use recursion. Check if the passed object is null and, if so, return null. Use Object.assign() and an empty object ({}) to create a shallow clone of the original. Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.

export const deepClone = (obj: any) => {
  if (obj === null) return null;
  let clone = { ...obj };
  Object.keys(clone).forEach(
    (key) =>
      (clone[key] =
        typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key])
  );
  return Array.isArray(obj) && obj.length
    ? (clone.length = obj.length) && Array.from(clone)
    : Array.isArray(obj)
    ? Array.from(obj)
    : clone;
};
const a = { foo: "bar", obj: { a: 1, b: 2 }, arr: [1, 2, 3] };
const b = deepClone(a); // a !== b, a.obj !== b.obj,
// a.arr[0] === b.arr[0]