Last active
April 27, 2022 11:19
-
-
Save neocotic/05bd3e7728fa27519d896e00e60ef25f to your computer and use it in GitHub Desktop.
Average Sampler
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
/** | |
* Generates sample data based on the `options` provided and then calculates the average based on the sample count. | |
* | |
* @param {Object} options - The options to be used. | |
* @param {function(): *} options.generator - The function to be used to generate data per round. | |
* @param {number} [options.roundsPerSample=1000] - The number of rounds in which `options.generator` is to be called per sampling. | |
* @param {function(value: *): boolean} options.sampler - The function to be used to filter samples from the generated data. | |
* @param {number} [options.samples=100] - The number of times samples should be run. | |
* @return {number} The calculated average. | |
*/ | |
function sampleAverage({ generator, roundsPerSample = 1000, sampler, samples = 100 }) { | |
function getSample() { | |
let i = roundsPerSample; | |
const results = []; | |
do { | |
const result = generator(); | |
if (sampler(result)) { | |
results.push(result); | |
} | |
} while (--i); | |
return results.length; | |
} | |
const counts = []; | |
do { | |
counts.push(getSample()); | |
} while (--samples); | |
return counts.reduce((sum, count) => sum + count, 0) / counts.length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An example usage for this is to see how likely it is that a UUID could start with
123
: