This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
5. implement throttle() with leading & trailing option

function throttle(func, delay, options) {
  let lastCallTime, timer, leadingCalled

  const { leading = true, trailing = true } = options || {}

  return function throttledFunction(...args) {
    const now = new Date().getTime()

    if (!lastCallTime && leading) {
      leadingCalled = true
      func.apply(this, args)
      lastCallTime = now
    } else {
      clearTimeout(timer)

      timer = setTimeout(() => {
        if (trailing || (now - lastCallTime >= delay)) {
          func.apply(this, args)
          lastCallTime = now
        }
      }, delay - (now - lastCallTime))
    }

    if (leading && leadingCalled) leadingCalled = false
  }
}

Explanation:

  • The throttle function accepts three arguments: the func to be throttled, the delay between two consecutive calls of func, and an optional options object with leading and trailing properties to control whether to invoke the function immediately and after waiting, respectively.
  • Inside throttle, we declare lastCallTime, timer, and leadingCalled variables to keep track of the previous invocation time, the current timeout timer, and whether the func has been called with the leading option, respectively.
  • We then return the throttledFunction, which accepts any number of arguments (...args) to be passed to func.
  • Inside throttledFunction, we get the current timestamp in milliseconds (now).
  • If lastCallTime is falsy (i.e., this is the first invocation) and leading is true, we set leadingCalled to true, invoke func with this context and args, and update lastCallTime with now.
  • Otherwise, we clear the previous timeout timer timer (if any), and set a new timer using setTimeout with a callback function that checks if trailing is true or if the delay between the current and previous invocations has passed. If so, we invoke func with this context and args, and update lastCallTime with now. Otherwise, we wait for the remaining time of delay - (now - lastCallTime) before invoking func.
  • Finally, if this call is with leading option and func has already been called, we set leadingCalled to false to prevent calling func again in the future.