import isArr from './isArr';

/**
 * 深拷贝一个对象或数组
 * @param {*} object 需要深拷贝的对象
 *
 * const obj = { str: 'string', obj: {}, arr: [] };
 * const obj2 = deepCopy(obj);        // => { str: 'string', obj: {}, arr: [] }
 * console.log(obj === obj2);         // false
 * console.log(obj.obj === obj2.obj); // false
 * console.log(isDeepEqual(obj === obj2)); // true
 */
function deepCopy(object) {
  var stack = [];

  var copy = function copy(obj) {
    if (!obj || typeof obj !== 'object') {
      return obj;
    }

    if (isArr(obj)) {
      return obj.map(function (item) {
        return copy(item);
      });
    }

    if (stack.indexOf(obj) > -1) {
      return obj.constructor && "[".concat(obj.constructor.name, "]");
    }

    stack.push(obj);
    var copied = {};
    Object.keys(obj).forEach(function (prop) {
      return copied[prop] = copy(obj[prop]);
    });
    return copied;
  };

  return copy(object);
}

export default deepCopy;
