addSome = (a, b) => {
  return a + b;
};

// 实现一个instanceof
Instanceof = (left, ringht) => {
  let a = left._proto_;
  let b = ringht.prototype;
  while (true) {
    if (a === null) return false;
    if (a === b) return true;
    a === a._proto_;
  }
};

//深拷贝 乞丐版
DeepCopyFirst = (obj) => {
  const newObj = JSON.parse(JSON.stringify(obj));
  return newObj;
};

//深拷贝 够用版
DeepCopySecond = (obj) => {
  if (typeof obj !== 'object' && typeof obj !== 'function') return obj;
  const newObj = Object.prototype.toString.call(obj) ? [] : {};
  for (let i in obj) {
    if (obj.hasOwnProperty(i)) {
      newObj[i] = typeof obj[i] === 'object' ? DeepCopySecond(objp[i]) : obj[i];
    }
  }
  return newObj;
};

//防抖 （连续点击 执行最后一次的点击）
// option.loading true 立即执行
Debounce = (func, time = 10, option = { loading: true, context: null }) => {
  let timer;
  const _debonce = (...args) => {
    if (timer) {
      clearTimeout(timer);
    }
    if (option.loading && !timer) {
      timer = setTimeout(null, time);
      func.apply(option.context, args); // 为了让 debounce 函数最终返回的函数 this 指向不变以及依旧能接受到 e 参数
    } else {
      timer = setTimeout(() => {
        func.apply(option.context, args);
        timer = null;
      }, time);
    }
  };
  _debonce.onCancel = () => {
    clearTimeout(timer);
    timer = null;
  };
  return _debonce;
};

// 节流
Throttle = (func, time = 10, option = { loading: true, trailing: false, context: null }) => {
  let timer;
  let previous = new Date(0).getTime();

  const _throttle = (...args) => {
    let newPrevious = new Date().getTime();
    if (!option.loading) {
      if (timer) return;
      timer = setTimeout(() => {
        timer = null;
        func.apply(option.context, args);
      }, time);
    } else if (newPrevious - previous > time) {
      func.apply(option.context, args);
      previous = newPrevious;
    } else if (option.trailing) {
      clearTimeout(timer);
      time = setTimeout(() => {
        func.apply(option.context, args);
      }, time);
    }
  };
  _throttle.onCancel = () => {
    previous = 0;
    clearTimeout(timer);
    timer = null;
  };
  return _throttle;
};

//实现一个map
Array.prototype.map = function (fn, thisArg) {
  // 数据异常处理
  if(this === null || this === undefined) {
    throw new TypeError('error');
  };
  //处理返回函数异常
  if (Object.prototype.toString.call(fn) !== '[object Function]') {
    throw new TypeError(`${fn} is not a function`);
  };
  // 对象转换
  let a = Object(this);
  let b = thisArg;
  let c = a.length >>> 0; // 保证c是数字且为整数
  let d = new Array(c);
  for (let e = 0; e < c; e++) {
    // in在原型链查找
    if (e in a) {
      let f = a[e];
      let g = fn.call(b, f, e, a);
      d = g;
    };
  };
  return d;
}
module.exports = {
  addSome,
  Instanceof,
  DeepCopyFirst,
  DeepCopySecond,
  Debounce,
  Throttle,
};
