この解答例はChatGPTによって生成されています,正しいかは自己判断で。

BFE.devでのAI解答例 - JavaScript コーディング問題
5. leading & trailingをサポートするthrottle() を実装する

以下は、leadingとtrailingのオプションを持つthrottle()の実装例です。

function throttle(func, wait, options = { leading: true, trailing: true }) {
  let context, args, result
  let timeout = null
  let previous = 0
  const { leading, trailing } = options

  const later = () => {
    previous = leading ? Date.now() : 0
    timeout = null
    result = func.apply(context, args)
    if (!timeout) context = args = null
  }

  const throttled = function (...rest) {
    const now = Date.now()
    if (!previous && !leading) previous = now
    const remaining = wait - (now - previous)
    context = this
    args = rest
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      previous = now
      result = func.apply(context, args)
      if (!timeout) context = args = null
    } else if (!timeout && trailing) {
      timeout = setTimeout(later, remaining)
    }
    return result
  }

  throttled.cancel = function () {
    clearTimeout(timeout)
    previous = 0
    timeout = context = args = null
  }

  return throttled
}