import { UnknownFunction } from '../Types'

/* eslint-disable prefer-rest-params */
export default function debounce(
  wait: number,
  fn: UnknownFunction,
): UnknownFunction {
  if (wait <= 0) {
    return fn
  }

  let timeoutId: number | undefined

  return function (this: UnknownFunction) {
    clearTimeout(timeoutId)

    timeoutId = setTimeout(() => {
      timeoutId = undefined
      fn.apply(this, [...arguments])
    }, wait)
  }
}
