Validate options on Exponential Backoff

This commit is contained in:
2026-07-18 16:24:00 +00:00
parent 448ef5ca61
commit 23ecfbd032
2 changed files with 187 additions and 3 deletions

View File

@@ -33,6 +33,8 @@ export class ExponentialBackoff {
jitter: 0.1,
...options,
};
ExponentialBackoff.validateOptions(this.#options);
}
/**
@@ -95,6 +97,60 @@ export class ExponentialBackoff {
return cappedDelay - jitter;
}
/**
* Validate the options for the exponential backoff
*
* @param options - The options to validate
*
* @throws An error if the options are invalid
*/
public static validateOptions(options: ExponentialBackoffOptions): void {
// Validate the max delay is a finite number not less than 0
if (!Number.isFinite(options.maxDelay)) {
throw new Error('maxDelay must be a finite number');
}
if (options.maxDelay < 0) {
throw new Error('maxDelay must be not less than 0');
}
// Validate the max attempts is a finite number not less than 0
if (!Number.isFinite(options.maxAttempts)) {
throw new Error('maxAttempts must be a finite number');
}
if (options.maxAttempts < 0) {
throw new Error('maxAttempts must be not less than 0');
}
// Validate the base delay is a finite number not less than 0
if (!Number.isFinite(options.baseDelay)) {
throw new Error('baseDelay must be a finite number');
}
if (options.baseDelay < 0) {
throw new Error('baseDelay must be not less than 0');
}
// Validate the growth rate is a finite number not less than 0
if (!Number.isFinite(options.growthRate)) {
throw new Error('growthRate must be a finite number');
}
if (options.growthRate < 0) {
throw new Error('growthRate must be not less than 0');
}
// Validate the jitter is a finite number not less than 0 or greater than 1
if (!Number.isFinite(options.jitter)) {
throw new Error('jitter must be a finite number');
}
if (options.jitter < 0 || options.jitter > 1) {
throw new Error('jitter must be not less than 0 or greater than 1');
}
}
/**
* Run the function with exponential backoff
*