@oxog/delay
Version:
A comprehensive, zero-dependency delay/timeout utility library with advanced timing features
38 lines • 1.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.addJitter = addJitter;
exports.randomBetween = randomBetween;
exports.calculateBackoffDelay = calculateBackoffDelay;
const index_js_1 = require("../types/index.js");
function addJitter(ms, jitter) {
if (jitter < 0 || jitter > 1) {
throw new index_js_1.DelayError(`Jitter must be between 0 and 1, got ${jitter}`, index_js_1.DelayErrorCode.INVALID_OPTIONS, { jitter });
}
const variation = ms * jitter;
const randomVariation = (Math.random() - 0.5) * 2 * variation;
return Math.max(0, ms + randomVariation);
}
function randomBetween(min, max) {
if (min > max) {
throw new index_js_1.DelayError(`Minimum value (${min}) cannot be greater than maximum value (${max})`, index_js_1.DelayErrorCode.INVALID_OPTIONS, { min, max });
}
if (min < 0 || max < 0) {
throw new index_js_1.DelayError(`Values cannot be negative. Min: ${min}, Max: ${max}`, index_js_1.DelayErrorCode.NEGATIVE_DELAY, { min, max });
}
return Math.random() * (max - min) + min;
}
function calculateBackoffDelay(baseDelay, attempt, strategy, factor = 2, maxDelay = Infinity) {
let delay;
switch (strategy) {
case 'linear':
delay = baseDelay * attempt;
break;
case 'exponential':
delay = baseDelay * Math.pow(factor, attempt - 1);
break;
default:
throw new index_js_1.DelayError(`Unknown backoff strategy: ${strategy}`, index_js_1.DelayErrorCode.INVALID_OPTIONS, { strategy });
}
return Math.min(delay, maxDelay);
}
//# sourceMappingURL=random.js.map