import "core-js/modules/es.promise.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import { useEffect, useRef, useCallback } from 'react';
const useUpdateEffect = (effect, deps) => {
  const isMounted = useRef(false);
  useEffect(() => {
    if (!isMounted.current) {
      isMounted.current = true;
    } else {
      return effect();
    }
    return () => undefined;
  }, deps);
};
function useDebounceFn(fn, deps, wait) {
  // eslint-disable-next-line no-underscore-dangle
  const hooksDeps = Array.isArray(deps) ? deps : [];
  // eslint-disable-next-line no-underscore-dangle
  const hookWait = typeof deps === 'number' ? deps : wait || 0;
  const timer = useRef();
  const fnRef = useRef(fn);
  fnRef.current = fn;
  const cancel = useCallback(() => {
    if (timer.current) {
      clearTimeout(timer.current);
    }
  }, []);
  const run = useCallback(async (...args) => {
    return new Promise(resolve => {
      cancel();
      timer.current = setTimeout(async () => {
        await fnRef.current(...args);
        resolve();
      }, hookWait);
    });
  }, [hookWait, cancel]);
  useUpdateEffect(() => {
    run();
    return cancel;
  }, [...hooksDeps, run]);
  useEffect(() => cancel, []);
  return {
    run,
    cancel
  };
}
export default useDebounceFn;