Hyperlinkv0.8.0-beta.28

Random

Random.nextIntBetweenconsteffect/Random.ts:187
(
  min: number,
  max: number,
  options?: { readonly halfOpen?: boolean }
): Effect.Effect<number>

Generates a random integer between min and max.

When to use

Use to generate a pseudo-random integer within a rounded numeric range.

Details

The lower bound is rounded up with Math.ceil and the upper bound is rounded down with Math.floor. By default the range is inclusive; set options.halfOpen: true to exclude the upper bound.

Example (Generating a bounded random integer)

import { Effect, Random } from "effect"

const program = Effect.gen(function*() {
  const diceRoll1 = yield* Random.nextIntBetween(1, 6)
  const diceRoll2 = yield* Random.nextIntBetween(1, 6, {
    halfOpen: true
  })
  const diceRoll3 = yield* Random.nextIntBetween(0, 10)
})
Random Number Generators
Source effect/Random.ts:18710 lines
export const nextIntBetween = (min: number, max: number, options?: {
  readonly halfOpen?: boolean
}): Effect.Effect<number> => {
  const extra = options?.halfOpen === true ? 0 : 1
  return randomWith((r) => {
    const minInt = Math.ceil(min)
    const maxInt = Math.floor(max)
    return Math.floor(r.nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt
  })
}