Sobes.tech
Middle

function cloneDeep(something: Cloneable): Cloneable { /* * TODO: implement deep clone without JSON.parse/stringify */ return JSON.parse(JSON.stringify(something)); } function assertDeep(a: Cloneable, b: Cloneable) { if (JSON.stringify(a) !== JSON.stringify(b)) { console.error("Not OK"); } console.log("OK"); } const obj: Cloneable = { a: 1, b: true, c: "hello", d: { there: "are", some: ["properties"] }, e: {}, f: [(), (), { key: { value: [1, 2, "3", "four"] } }], g: [] }; assertDeep(obj, cloneDeep(obj));

sobes.tech AI

Answer from AI

To implement deep cloning without using JSON.parse(JSON.stringify(...)), you can write a recursive function that copies objects, arrays, and primitives. It's important to consider cyclic references and data types, but for simplicity, we'll implement a basic version without cycle support.

function cloneDeep(something: any): any {
  if (something === null || typeof something !== 'object') {
    return something; // Return primitives as is
  }

  if (Array.isArray(something)) {
    return something.map(item => cloneDeep(item));
  }

  const clonedObj: any = {};
  for (const key in something) {
    if (Object.prototype.hasOwnProperty.call(something, key)) {
      clonedObj[key] = cloneDeep(something[key]);
    }
  }
  return clonedObj;
}

function assertDeep(a: any, b: any) {
  if (JSON.stringify(a) !== JSON.stringify(b)) {
    console.error("Not OK");
  } else {
    console.log("OK");
  }
}

const obj = {
  a: 1,
  b: true,
  c: "hello",
  d: {
    there: "are",
    some: ["properties"]
  },
  e: {},
  f: [null, null, { key: { value: [1, 2, "3", "four"] } }],
  g: []
};

assertDeep(obj, cloneDeep(obj));

Note that in the original code, there were invalid calls () in the array, which I replaced with null for correctness.

This code recursively copies objects and arrays, creating a deep copy without using JSON serialization.

function cloneDeep(something: Cloneable): Cloneable {… - sobes.tech