{"size": 1149, "ext": "js", "max_stars_repo_path": "src/index.js", "max_stars_repo_name": "Financial-Times/scroll-tracking", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/index.js", "max_issues_repo_name": "Financial-Times/scroll-tracking", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/index.js", "max_forks_repo_name": "Financial-Times/scroll-tracking", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.4615384615, "max_line_length": 78, "alphanum_fraction": 0.6727589208}
const throttle = require('lodash/throttle');
const isEqual = require('lodash/isEqual');

function getPercentageViewable (element) {
  const rect = element.getBoundingClientRect();
  const percentage = (100 / rect.height) * (window.innerHeight - rect.top);
  return percentage === Infinity ? 0 : percentage;

}

module.exports = (function() {
  let _scrollHandler;
  let _currentBuckets;

  class ScrollTracker {
    constructor({element, buckets, callback, delay}) {
      this.rootEl = element;
      this.rootEl.dataset.scrollTracking = true;
      _scrollHandler = throttle(() => {
        const percentage = getPercentageViewable(element);
        const currentBuckets = buckets.filter(bucket => bucket <= percentage);
        if (!isEqual(currentBuckets, _currentBuckets)) {
          _currentBuckets = currentBuckets;
          callback(currentBuckets);
        }
      }, delay);
      document.addEventListener('scroll', _scrollHandler);
    }

    destroy () {
      document.removeEventListener('scroll', _scrollHandler);
      delete this.rootEl.dataset.scrollTracking;
      delete this.rootEl;
    }
  };

  return ScrollTracker;
}());
