A utility for generating lots of random numbers without being too tasking on the browser. Randomly accomplishes this by generating a set of random numbers on a given interval.
Subsequent requests for random numbers are served from the generated set instead of calling Math.random
. In addition to getting random numbers, some useful methods have also been added around random numbers.
Working on several generative art projects inspired the need for a common utility which would handle very frequent calls to Math.random
as well as other provided methods which involve using random numbers.
Why not just use Math.random
? Depending on how many numbers are being generated Randomly
tends to be more performant as frequency increases. The following chart shows their comparison. You can view how this was measured in the benchmark.ts file.
import Randomly from '@ededejr/randomly';
const randomly = new Randomly();
randomly.get(); // Returns a number between 0 and 1
randomly.compare((value) => Math.floor(value * 1000) > 500);
randomly.lt(0.2);
randomly.gt(0.2);
randomly.between(0.2, 0.6);
randomly.decide('Option A', 'Option B');
randomly.sample(100);
If you would like to pause the interval:
randomly.stopTimer();
Starting it up again:
randomly.startTimer();
import Randomly from '@ededejr/randomly';
const randomly = new Randomly({
refreshInterval: 5000, // refresh random number store every 5 seconds
storeSize: 100, // keep a store of a 100 random numbers
});