Skip to content

Instantly share code, notes, and snippets.

@neocotic
Last active April 27, 2022 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neocotic/05bd3e7728fa27519d896e00e60ef25f to your computer and use it in GitHub Desktop.
Save neocotic/05bd3e7728fa27519d896e00e60ef25f to your computer and use it in GitHub Desktop.
Average Sampler
/**
* 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;
}
@neocotic
Copy link
Author

neocotic commented Apr 27, 2022

An example usage for this is to see how likely it is that a UUID could start with 123:

sampleAverage({
  generator: () => crypto.randomUUID(),
  sampler: (value) => /^123/.test(value)
})
// 0.25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment