1

I am trying to implement a clone function but I am not sure if I am doing it right while trying to clone '[object Function]'. You will see the result at the bottom. I am not sure if desired result should look like the original input data. Let me know what you think and if you have any ideas on how to implement it. Here is the code.

UPD: actually it works as it supposed to be working. I am going to leave it here so people can use it if they have the same question.

function deep(value) {
  if (typeof value !== 'object' || value === null) {
    return value;
  }

  if (Array.isArray(value)) {
    return deepArray(value);
  }

  return deepObject(value);
}

function deepObject(source) {
  const result = {};

  Object.keys(source).forEach(key => {
    const value = source[key];

    result[key] = deep(value);
  });

  return result;
}

function deepArray(collection) {
  return collection.map(value => {
    return deep(value);
  });
}

const id1 = Symbol('id');
const value = {
  a: 2,
  f: id1,
  b: '2',
  c: false,
  g: [
    { a: { j: undefined }, func: () => {} },
    { a: 2, b: '2', c: false, g: [{ a: { j: undefined }, func: () => {} }] }
  ]
};

RESULT

{ a: 2,
  f: Symbol(id),
  b: '2',
  c: false,
  g:
   [ { a: { j: undefined }, func: [Function: func] },
     { a: 2,
       b: '2',
       c: false,
       g: [ { a: { j: undefined }, func: [Function: func] } ] } ] }
John John
  • 1,305
  • 2
  • 16
  • 37

2 Answers2

1

You cannot clone an arrow function, when you clone an object that has arrow functions as properties they will always be bound to the object they were created in, you cannot rebind them, that is the whole point of an arrow function, predictable behaviour of the this object. If you want to clone objects then make sure that any functions that refer to this are normal functions and not arrow functions.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

Better use below single code for deepcopy -

function deepCopy(oldObj) {
   var newObj = oldObj;
   if (oldObj && typeof oldObj === "object") {
       newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
       for (var i in oldObj) {
           newObj[i] = this.deepCopy(oldObj[i]);
       }
   }
   return newObj;
}
Samyak Jain
  • 856
  • 1
  • 9
  • 12