import "core-js/modules/es.promise.js";
/**
 * 防抖 函数实现
 * 异步函数如何处理
 * @param fn
 * @param delay
 * @param immediate
 * @param context
 */
export function debounce(fn, delay, immediate = true, context) {
  // 不是函数 抛出错误
  if (typeof fn !== 'function') {
    throw new Error('fn is not function');
  }
  let timer;
  // 第一次触发事件是否立即执行
  let _immediate = immediate;
  return function (...args) {
    // 解决fn 是异步函数的问题
    return new Promise((resolve, reject) => {
      try {
        if (_immediate) {
          // @ts-ignore
          const result = fn.apply(this, args);
          _immediate = false;
          resolve(result);
        }
        clearTimeout(timer);
        timer = setTimeout(async () => {
          const data = await fn.apply(context, args);
          resolve(data);
        }, delay);
      } catch (e) {
        reject(e);
      }
    });
  };
}