All files / random / between.ts

100.00% Branches 11/11
100.00% Lines 20/20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x11
x11
x11
x11
 
x30125
x30129
x30129
 
x30129
x30125
x30129
x30129
 
x30129
x30125
x30127
x30127
 
x30127
 
x30125
x30125
x30125
x30125

















































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
import type { Prng, RandomOptions } from "./_types.ts";
export type { Prng, RandomOptions };

/**
 * Generates a random number between the provided minimum and maximum values.
 *
 * The number is in the range `[min, max)`, i.e. `min` is included but `max` is excluded.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param min The minimum value (inclusive)
 * @param max The maximum value (exclusive)
 * @param options The options for the random number generator
 * @returns A random number between the provided minimum and maximum values
 *
 * @example Usage
 * ```ts no-assert
 * import { randomBetween } from "@std/random";
 *
 * randomBetween(1, 10); // 6.688009464410508
 * randomBetween(1, 10); // 3.6267118101712006
 * randomBetween(1, 10); // 7.853320239013774
 * ```
 */
export function randomBetween(
  min: number,
  max: number,
  options?: RandomOptions,
): number {
  if (!Number.isFinite(min)) {
    throw new RangeError(
      `Cannot generate a random number: min cannot be ${min}`,
    );
  }
  if (!Number.isFinite(max)) {
    throw new RangeError(
      `Cannot generate a random number: max cannot be ${max}`,
    );
  }
  if (max < min) {
    throw new RangeError(
      `Cannot generate a random number as max must be greater than or equal to min: max=${max}, min=${min}`,
    );
  }

  const x = (options?.prng ?? Math.random)();
  const y = min * (1 - x) + max * x;
  return y >= min && y < max ? y : min;
}