crypto.randomInt Draws Bounded Integers

Draw bounded integers with crypto.randomInt, where the upper bound is exclusive, avoiding the modulo bias that hand-rolled Math.random tricks introduce.

JavascriptSecurity Boundaries

Code

javascriptsnippet
18 lines
import { randomInt } from 'node:crypto';

// randomInt(max) draws from [0, max); with two bounds the upper one is excluded
const dice = randomInt(1, 7); // [1, 7) -> 1..6
console.log('dice in range:', dice >= 1 && dice <= 6);

// Range holds across many draws
let inBounds = true;
for (let i = 0; i < 1000; i++) {
  const value = randomInt(10, 20);
  if (value < 10 || value >= 20) inBounds = false;
}
console.log('1000 draws all in [10, 20):', inBounds);

// small ranges collect every face quickly without modulo bias
const seen = new Set();
while (seen.size < 6) seen.add(randomInt(1, 7));
console.log('collected all six faces:', seen.size === 6);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

dice in range: true
1000 draws all in [10, 20): true
collected all six faces: true

Inside the snippet

The nesting pairs for (let i = 0; i < 1000; i++) with while (seen.size < 6) seen.add(randomInt(1, 7)); — the inner runs once per outer step. randomInt comes from node:crypto — Node.js core modules the runtime ships with.

Every operation runs against top-level bindings: dice, inBounds, seen.

Points of care

  • The dependency surface is just node:crypto, and that one is built into Node.js.
  • A browser is the runtime here: crypto are not available in Node.

Using it

The demo output is labeled (dice in range:, 1000 draws all in [10, 20):, collected all six faces:), so each printed line points back to the operation that produced it.

Key statements

const seen = new Set();

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:crypto`, and that is a Node.js built-in — it comes with the runtime.