Created
February 9, 2021 11:05
-
-
Save xxzefgh/2b35e7bc56e15fc02964b79be6914bc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function exponentialRandomBackoff( | |
initialIntervalMillis: number, | |
multiplier: number, | |
randomizationFactor: number | |
) { | |
checkInterval(initialIntervalMillis); | |
checkMultiplier(multiplier); | |
checkRandomizationFactor(randomizationFactor); | |
return (attemptsMade: number) => { | |
const interval = Math.round(Math.pow(multiplier, attemptsMade) * initialIntervalMillis); | |
return randomize(interval, randomizationFactor); | |
}; | |
} | |
function randomize(current: number, randomizationFactor: number): number { | |
let delta = randomizationFactor * current; | |
let min = current - delta; | |
let max = current + delta; | |
return min + Math.random() * (max - min + 1); | |
} | |
function checkInterval(interval: number) { | |
if (interval < 10) { | |
throw new RangeError('Illegal argument interval: ' + interval + ' millis'); | |
} | |
} | |
function checkMultiplier(multiplier: number) { | |
if (multiplier < 1.0) { | |
throw new RangeError('Illegal argument multiplier: ' + multiplier); | |
} | |
} | |
function checkRandomizationFactor(randomizationFactor: number) { | |
if (randomizationFactor < 0.0 || randomizationFactor >= 1.0) { | |
throw new RangeError('Illegal argument randomizationFactor: ' + randomizationFactor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment