'use strict';

/*!
 * @techmely/utils
 * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com>
 * MIT Licensed
 */


// src/getRandomInt.ts
function getRandomInt(min, max) {
  const _min = Math.ceil(min);
  const _max = Math.floor(max);
  return Math.floor(Math.random() * (_max - _min) + _min);
}

// src/p.delay.ts
var createAbortError = () => {
  const error = new Error("Delay aborted");
  error.name = "AbortError";
  return error;
};
var clearMethods = /* @__PURE__ */ new WeakMap();
function delay(milliseconds, options) {
  return createDelay(milliseconds, options);
}
function createDelay(milliseconds, { value, signal } = {}) {
  if (signal?.aborted) {
    return Promise.reject(createAbortError());
  }
  let timeoutId;
  let settle;
  let rejectFunction;
  const signalListener = () => {
    clearTimeout(timeoutId);
    rejectFunction(createAbortError());
  };
  const cleanup = () => {
    if (signal) {
      signal.removeEventListener("abort", signalListener);
    }
  };
  const delayPromise = new Promise((resolve, reject) => {
    settle = () => {
      cleanup();
      if (value)
        resolve(value);
    };
    rejectFunction = reject;
    timeoutId = setTimeout(settle, milliseconds);
  });
  if (signal) {
    signal.addEventListener("abort", signalListener, { once: true });
  }
  clearMethods.set(delayPromise, () => {
    clearTimeout(timeoutId);
    timeoutId = void 0;
    settle();
  });
  return delayPromise;
}
async function rangeDelay(minimum, maximum, options = {}) {
  return delay(getRandomInt(minimum, maximum), options);
}
function clearDelay(promise) {
  clearMethods.get(promise)?.();
}

exports.clearDelay = clearDelay;
exports.createDelay = createDelay;
exports.delay = delay;
exports.rangeDelay = rangeDelay;
