Technical skill practice

JavaScript Math.random: Map a Fraction to an Integer Range

Math.random produces a fraction from zero up to but excluding one. To select a bounded integer, define the interval and map that fraction deliberately. Test the arithmetic with supplied fractions instead of asserting one unpredictable draw.

The task

Choose an integer from four through nine, inclusive. Inject the fractional source so boundary tests remain repeatable, then check a real draw only for its supported range.

Runnable Node 22 example

const assert = require('node:assert/strict');

function pick(low, high, random = Math.random) {
  assert(Number.isInteger(low) && Number.isInteger(high) && high >= low);
  const fraction = random();
  assert(fraction >= 0 && fraction < 1);
  return low + Math.floor(fraction * (high - low + 1));
}
assert.equal(pick(4, 9, () => 0), 4);
assert.equal(pick(4, 9, () => 0.5), 7);
assert.equal(pick(4, 9, () => 0.999999), 9);
const actual = Math.random();
assert(actual >= 0 && actual < 1);
console.log([0, 0.5, 0.999999].map(value => pick(4, 9, () => value)).join(','));

Expected output and explanation

There are six candidate integers, so multiplying by six creates six intervals before floor selects a position. Adding the lower bound shifts that position into the requested range. Testing fractions near both ends catches missing +1 and upper-bound mistakes.

The printed values are deterministic because those calls use injected fractions. The separate real draw is checked without printing a guessed value. These assertions establish the mapping for the selected boundaries, not statistical fairness of a large random experiment.

Output from the example

4,7,9

Pitfall to check

This helper assumes a modest interval within safe arithmetic limits. Do not use Math.random for secrets, security tokens or cryptographic choices; use the appropriate cryptographic API and its documented contract.

Questions, answered

Why not use Math.round on the scaled fraction?

That gives edge intervals different widths in the usual inclusive-range formula. Floor with a stated interval makes the intended mapping easier to inspect.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.