Picking a random item, rolling a die in a game, choosing a placeholder avatar color: each one turns Math.random(), a fraction from 0 up to (but not including) 1, into a whole number in a range. The conversion is easy to get slightly wrong, and the result still looks random: the highest value never appears, or the two ends come up half as often as the others.
Write two functions in random.js: randomInt(min, max) and randomHexColor().
randomInt returns an integer from min to max, both included: min when Math.random() gives 0, max when it gives a number just below 1.
Every integer in the range is equally likely: evenly spread random numbers give each value the same count.
It works for negative ranges and for a range of one value (min === max).
A bound with a fraction is moved inward: min is rounded up and max down, so randomInt(1.5, 4.5) gives 2, 3 or 4.
randomInt calls Math.random exactly once.
randomInt throws a RangeError when min is greater than max, when no integer lies between them (randomInt(1.2, 1.8)), or when a bound is NaN or infinite.
randomHexColor multiplies Math.random() by 16,777,216, takes the floor, converts that integer to six lower-case hexadecimal digits (padded with zeros in front), and prefixes #. It calls Math.random exactly once.
Different random values can map to the same color. The two ends are "#000000" (when Math.random() gives 0) and "#ffffff" (when it gives a number just below 1).
Plain JavaScript in a browser page; the tests call the globals randomInt and randomHexColor from random.js.
Most tests replace Math.random with a function that returns chosen numbers, so use Math.random (not crypto.getRandomValues).
Bounds are small enough to be exact: the tests use ranges of at most a hundred integers. Near Number.MAX_SAFE_INTEGER, numbers can no longer hold every integer, and Math.random has too few distinct values to reach every integer of a huge range evenly.