Created
September 13, 2018 15:25
-
-
Save lloydjatkinson/b7e73f8f1d7ca3c0a37cf0a93791b6d4 to your computer and use it in GitHub Desktop.
back-off.js
This file contains 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
/** | |
* Generalised back-off function. | |
* @param {Function} unary The unary operator function that returns the next state given the current state (current value and invocation count). | |
* @param {Number} initial The initial value to start the back-off. | |
* @example const multiplyTenBackOff = backOff((current, count) => current * 10); | |
* @example const negativeBackOff = backOff((current, count) => current - 1, 1000); | |
*/ | |
const backOff = (unary, initial = 0) => { | |
let current = initial; | |
let count = 0; | |
const func = () => { | |
count = count + 1; | |
current = unary(current, count); | |
return current; | |
}; | |
return func; | |
}; | |
/** | |
* Incremental back-off function. | |
* @param {Number} increment The amount to increment the back-off. | |
* @param {Number} initial The initial value to start the back-off. | |
*/ | |
const incrementalBackOff = (increment = 1, initial = 0) => { | |
let current = initial; | |
const func = () => { | |
current = current + increment; | |
return current; | |
}; | |
return func; | |
}; | |
/** | |
* Incremental back-off function with random jitter to avoid collision. | |
* @param {Number} increment The amount to increment the back-off. | |
* @param {Number} initial The initial value to start the back-off. | |
*/ | |
const incrementalJitterBackOff = (increment = 1, initial = 1) => { | |
let current = initial; | |
const func = () => { | |
current = current + increment + Math.round(Math.random() * 100); | |
return current; | |
}; | |
return func; | |
}; | |
export { | |
backOff, | |
incrementalBackOff, | |
incrementalJitterBackOff | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment