"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var headSampler_exports = {};
__export(headSampler_exports, {
  HeadSampler: () => HeadSampler
});
module.exports = __toCommonJS(headSampler_exports);
const normalize = (percent) => {
  if (typeof percent !== "number" || Number.isNaN(percent)) return 0;
  if (percent >= 100) return 100;
  if (percent <= 0) return 0;
  return percent;
};
const convertToDivisibleBy5 = (percent) => Math.round(normalize(percent) / 5) * 5;
const percentToFraction = (percent) => {
  const numerator = percent;
  const denominator = 100;
  const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
  const divisor = gcd(numerator, denominator);
  return { numerator: numerator / divisor, denominator: denominator / divisor };
};
class HeadSampler {
  /**
   * Upper bound of the sampling size
   */
  #upperBound = 0;
  /**
   * Total size of the sampling
   */
  #totalSize = 0;
  /**
   * Number of events sampled
   */
  #sampled = 0;
  /**
   * Creates new instance of HeadSampler
   * @param samplingPercent sampling percentage
   */
  constructor(samplingPercent) {
    const value = percentToFraction(convertToDivisibleBy5(samplingPercent));
    this.#upperBound = value.numerator;
    this.#totalSize = value.denominator;
  }
  /**
   * check if the event should be sampled
   * @returns true if the event should be sampled
   */
  shouldSample = () => {
    this.#sampled += 1;
    if (this.#sampled <= this.#upperBound) return true;
    if (this.#sampled === this.#totalSize) this.#sampled = 0;
    return false;
  };
}
