'use strict';

const React = require('react');

function useThrottle(callback, delay) {
  const lastRan = React.useRef(Date.now());
  const timeoutRef = React.useRef(null);
  return React.useCallback(
    (...args) => {
      const handler = () => {
        if (Date.now() - lastRan.current >= delay) {
          callback(...args);
          lastRan.current = Date.now();
        } else {
          if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
          }
          timeoutRef.current = setTimeout(
            () => {
              callback(...args);
              lastRan.current = Date.now();
            },
            delay - (Date.now() - lastRan.current)
          );
        }
      };
      handler();
    },
    [callback, delay]
  );
}

exports.useThrottle = useThrottle;
