Open History to see the last commit
1/**
2 * Provides pseudo-random generation through an Effect service.
3 *
4 * This module exposes effectful generators for booleans, doubles, safe
5 * integers, bounded numbers, shuffling, and deterministic seeded runs. Because
6 * random generation is a service, tests and applications can replace the
7 * generator used by Effect programs.
8 *
9 * @since 4.0.0
10 */
11import type * as Arr from "./Array.ts"
12import * as Cause from "./Cause.ts"
13import type * as Context from "./Context.ts"
14import * as Effect from "./Effect.ts"
15import { dual } from "./Function.ts"
16import * as random from "./internal/random.ts"
17import type * as NonEmptyIterable from "./NonEmptyIterable.ts"
18import * as Predicate from "./Predicate.ts"
19
20/**
21 * Represents a service for generating pseudo-random numbers.
22 *
23 * **When to use**
24 *
25 * Use to access or provide the random-number generator service used by Effect
26 * programs.
27 *
28 * **Gotchas**
29 *
30 * The default implementation is based on `Math.random` and is not
31 * cryptographically secure. Replace the service with a cryptographically secure
32 * implementation before using these generators for security-sensitive values.
33 *
34 * **Example** (Accessing the random service)
35 *
36 * ```ts
37 * import { Effect, Random } from "effect"
38 *
39 * const program = Effect.gen(function*() {
40 * const float = yield* Random.next
41 * const integer = yield* Random.nextInt
42 * const inRange = yield* Random.nextIntBetween(1, 100)
43 *
44 * console.log("Float:", float)
45 * console.log("Integer:", integer)
46 * console.log("In range:", inRange)
47 * })
48 * ```
49 *
50 * @category Random Number Generators
51 * @since 2.0.0
52 */
53export const Random: Context.Reference<{
54 nextIntUnsafe(): number
55 nextDoubleUnsafe(): number
56}> = random.Random
57
58const randomWith = <A>(f: (random: typeof Random["Service"]) => A): Effect.Effect<A> =>
59 Effect.withFiber((fiber) => Effect.succeed(f(fiber.getRef(Random))))
60
61/**
62 * Generates a random number between 0 (inclusive) and 1 (exclusive).
63 *
64 * **When to use**
65 *
66 * Use to generate a pseudo-random floating-point number in the standard
67 * `[0, 1)` range.
68 *
69 * **Example** (Generating a random number)
70 *
71 * ```ts
72 * import { Effect, Random } from "effect"
73 *
74 * const program = Effect.gen(function*() {
75 * const randomDouble = yield* Random.next
76 * console.log("Random double:", randomDouble)
77 * })
78 * ```
79 *
80 * @category Random Number Generators
81 * @since 2.0.0
82 */
83export const next: Effect.Effect<number> = randomWith((r) => r.nextDoubleUnsafe())
84
85/**
86 * Generates a random boolean value.
87 *
88 * **When to use**
89 *
90 * Use to make a pseudo-random true-or-false choice.
91 *
92 * **Example** (Generating a random boolean)
93 *
94 * ```ts
95 * import { Effect, Random } from "effect"
96 *
97 * const program = Effect.gen(function*() {
98 * const value = yield* Random.nextBoolean
99 * console.log("Random boolean:", value)
100 * })
101 * ```
102 *
103 * @category Random Number Generators
104 * @since 2.0.0
105 */
106export const nextBoolean: Effect.Effect<boolean> = randomWith((r) => r.nextDoubleUnsafe() > 0.5)
107
108/**
109 * Generates a random integer between `Number.MIN_SAFE_INTEGER` (inclusive)
110 * and `Number.MAX_SAFE_INTEGER` (inclusive).
111 *
112 * **When to use**
113 *
114 * Use to generate a pseudo-random safe integer across the full safe-integer
115 * range.
116 *
117 * **Example** (Generating a random integer)
118 *
119 * ```ts
120 * import { Effect, Random } from "effect"
121 *
122 * const program = Effect.gen(function*() {
123 * const randomInt = yield* Random.nextInt
124 * console.log("Random integer:", randomInt)
125 * })
126 * ```
127 *
128 * @category Random Number Generators
129 * @since 2.0.0
130 */
131export const nextInt: Effect.Effect<number> = randomWith((r) => r.nextIntUnsafe())
132
133/**
134 * Generates a random number between `min` (inclusive) and `max` (exclusive).
135 *
136 * **When to use**
137 *
138 * Use to generate a pseudo-random floating-point number within a numeric range.
139 *
140 * **Example** (Generating a bounded random number)
141 *
142 * ```ts
143 * import { Effect, Random } from "effect"
144 *
145 * const program = Effect.gen(function*() {
146 * const randomDouble = yield* Random.nextBetween(0, 1)
147 * console.log("Random double: ", randomDouble)
148 * })
149 * ```
150 *
151 * @category Random Number Generators
152 * @since 4.0.0
153 */
154export const nextBetween = (min: number, max: number): Effect.Effect<number> =>
155 randomWith((r) => r.nextDoubleUnsafe() * (max - min) + min)
156
157/**
158 * Generates a random integer between `min` and `max`.
159 *
160 * **When to use**
161 *
162 * Use to generate a pseudo-random integer within a rounded numeric range.
163 *
164 * **Details**
165 *
166 * The lower bound is rounded up with `Math.ceil` and the upper bound is
167 * rounded down with `Math.floor`. By default the range is inclusive; set
168 * `options.halfOpen: true` to exclude the upper bound.
169 *
170 * **Example** (Generating a bounded random integer)
171 *
172 * ```ts
173 * import { Effect, Random } from "effect"
174 *
175 * const program = Effect.gen(function*() {
176 * const diceRoll1 = yield* Random.nextIntBetween(1, 6)
177 * const diceRoll2 = yield* Random.nextIntBetween(1, 6, {
178 * halfOpen: true
179 * })
180 * const diceRoll3 = yield* Random.nextIntBetween(0, 10)
181 * })
182 * ```
183 *
184 * @category Random Number Generators
185 * @since 2.0.0
186 */
187export const nextIntBetween = (min: number, max: number, options?: {
188 readonly halfOpen?: boolean
189}): Effect.Effect<number> => {
190 const extra = options?.halfOpen === true ? 0 : 1
191 return randomWith((r) => {
192 const minInt = Math.ceil(min)
193 const maxInt = Math.floor(max)
194 return Math.floor(r.nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt
195 })
196}
197
198/**
199 * Uses the pseudo-random number generator to shuffle the specified iterable.
200 *
201 * **When to use**
202 *
203 * Use to randomly reorder an iterable using the active `Random` service.
204 *
205 * **Example** (Shuffling values)
206 *
207 * ```ts
208 * import { Effect, Random } from "effect"
209 *
210 * const program = Effect.gen(function*() {
211 * const values = yield* Random.shuffle([1, 2, 3, 4, 5])
212 * console.log(values)
213 * })
214 * ```
215 *
216 * @category Random Number Generators
217 * @since 2.0.0
218 */
219export const shuffle = <A>(elements: Iterable<A>): Effect.Effect<Array<A>> =>
220 randomWith((r) => {
221 const buffer = Array.from(elements)
222 for (let i = buffer.length - 1; i >= 1; i = i - 1) {
223 const index = Math.min(i, Math.floor(r.nextDoubleUnsafe() * (i + 1)))
224 const value = buffer[i]!
225 buffer[i] = buffer[index]!
226 buffer[index] = value
227 }
228 return buffer
229 })
230
231/**
232 * Gets a random element from an iterable.
233 *
234 * **When to use**
235 *
236 * Use to select one value uniformly from a collection using the active `Random`
237 * service.
238 *
239 * **Details**
240 *
241 * If the input type is known to be non-empty, the returned effect cannot fail.
242 * Otherwise, empty iterables fail with `Cause.NoSuchElementError`.
243 *
244 * **Example** (Choosing a random value)
245 *
246 * ```ts
247 * import { Effect, Random } from "effect"
248 *
249 * const program = Effect.gen(function*() {
250 * const value = yield* Random.choice(["red", "green", "blue"] as const)
251 * console.log(value)
252 * })
253 * ```
254 *
255 * @category Random Number Generators
256 * @since 3.6.0
257 */
258export const choice: <Self extends Iterable<unknown>>(
259 elements: Self
260) => Self extends NonEmptyIterable.NonEmptyIterable<infer A> ? Effect.Effect<A>
261 : Self extends Arr.NonEmptyReadonlyArray<infer A> ? Effect.Effect<A>
262 : Self extends Iterable<infer A> ? Effect.Effect<A, Cause.NoSuchElementError>
263 : never = ((elements: Iterable<unknown>) => {
264 const buffer = Array.from(elements)
265 return buffer.length === 0
266 ? Effect.fail(new Cause.NoSuchElementError("Cannot select a random element from an empty array"))
267 : randomWith((r) => buffer[Math.min(buffer.length - 1, Math.floor(r.nextDoubleUnsafe() * buffer.length))]!)
268 }) as any
269
270/**
271 * Seeds the pseudo-random number generator with the specified value.
272 *
273 * **When to use**
274 *
275 * Use to run an effect with a deterministic pseudo-random sequence.
276 *
277 * **Details**
278 *
279 * Using the same seed produces the same random sequence, which is useful for
280 * tests and reproducible simulations.
281 *
282 * **Gotchas**
283 *
284 * Use an unpredictable seed when uniqueness or unpredictability matters.
285 *
286 * **Example** (Seeding random generation)
287 *
288 * ```ts
289 * import { Effect, Random } from "effect"
290 *
291 * const program = Effect.gen(function*() {
292 * const value1 = yield* Random.next
293 * const value2 = yield* Random.next
294 * console.log(value1, value2)
295 * })
296 *
297 * // Same seed produces same sequence
298 * const seeded1 = program.pipe(Random.withSeed("my-seed"))
299 * const seeded2 = program.pipe(Random.withSeed("my-seed"))
300 *
301 * // Both will output identical values
302 * Effect.runPromise(seeded1)
303 * Effect.runPromise(seeded2)
304 * ```
305 *
306 * @category Seeding
307 * @since 4.0.0
308 */
309export const withSeed: {
310 (seed: string | number): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
311 <A, E, R>(self: Effect.Effect<A, E, R>, seed: string | number): Effect.Effect<A, E, R>
312} = dual(2, <A, E, R>(
313 self: Effect.Effect<A, E, R>,
314 seed: string | number
315) => Effect.provideService(self, Random, ISAAC_CSPRNG(seed)))
316
317/*///////////////////////////////////////////////////////////////////////////////////////////////////
318This is a derivative work copyright (c) 2025 Effectful Technologies Inc, under MIT license.
319This is a derivative work copyright (c) 2018, William P. "Mac" McMeans, under BSD license.
320Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
3211. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
3222. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3233. Neither the name of isaacCSPRNG nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
324THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
325Original work copyright (c) 2012 Yves-Marie K. Rinquin, under MIT license.
326https://github.com/rubycon/isaac.js
327///////////////////////////////////////////////////////////////////////////////////////////////////*/
328function ISAAC_CSPRNG(userSeed?: string | number) {
329 // Internal State
330 const memory = new Array(256)
331 const result = new Array(256)
332 let accumulator = 0
333 let lastResult = 0
334 let generation = 0
335 let counter = 0
336
337 // Initial Seed
338 const internalSeed = Predicate.isUndefined(userSeed) ? getInitialSeed() : userSeed
339 seed(internalSeed)
340
341 function getInitialSeed() {
342 const uint32a = new Uint32Array(2)
343 crypto.getRandomValues(uint32a)
344 return uint32a[0] + uint32a[1]
345 }
346
347 function reset() {
348 accumulator = 0
349 lastResult = 0
350 counter = 0
351 for (let i = 0; i < 256; ++i) {
352 memory[i] = 0
353 result[i] = 0
354 }
355 generation = 0
356 }
357
358 function seed(userSeed: string | number): void {
359 // The golden ratio ( 2654435769 )
360 // See https://stackoverflow.com/questions/4948780/magic-number-in-boosthash-combine
361 const magicNumber = 0x9e3779b9
362 let a = magicNumber
363 let b = magicNumber
364 let c = magicNumber
365 let d = magicNumber
366 let e = magicNumber
367 let f = magicNumber
368 let g = magicNumber
369 let h = magicNumber
370 let i = 0
371
372 let seed: Array<number>
373 if (Predicate.isString(userSeed)) {
374 seed = toIntArray(userSeed)
375 } else {
376 seed = [userSeed]
377 }
378
379 reset()
380
381 for (i = 0; i < seed.length; i++) {
382 result[i & 0xff] += seed[i]
383 }
384
385 function mix() {
386 a ^= b << 11
387 d = add32(d, a)
388 b = add32(b, c)
389
390 b ^= c >>> 2
391 e = add32(e, b)
392 c = add32(c, d)
393
394 c ^= d << 8
395 f = add32(f, c)
396 d = add32(d, e)
397
398 d ^= e >>> 16
399 g = add32(g, d)
400 e = add32(e, f)
401
402 e ^= f << 10
403 h = add32(h, e)
404 f = add32(f, g)
405
406 f ^= g >>> 4
407 a = add32(a, f)
408 g = add32(g, h)
409
410 g ^= h << 8
411 b = add32(b, g)
412 h = add32(h, a)
413
414 h ^= a >>> 9
415 c = add32(c, h)
416 a = add32(a, b)
417 }
418
419 // Scramble the seed
420 for (i = 0; i < 4; i++) {
421 mix()
422 }
423
424 for (i = 0; i < 256; i += 8) {
425 // Use all the information in the seed
426 a = add32(a, result[i])
427 b = add32(b, result[i + 1])
428 c = add32(c, result[i + 2])
429 d = add32(d, result[i + 3])
430 e = add32(e, result[i + 4])
431 f = add32(f, result[i + 5])
432 g = add32(g, result[i + 6])
433 h = add32(h, result[i + 7])
434
435 mix()
436
437 // Fill in the memory with messy stuff
438 memory[i] = a
439 memory[i + 1] = b
440 memory[i + 2] = c
441 memory[i + 3] = d
442 memory[i + 4] = e
443 memory[i + 5] = f
444 memory[i + 6] = g
445 memory[i + 7] = h
446 }
447
448 // Second pass to make sure seed affects memory
449 for (i = 0; i < 256; i += 8) {
450 a = add32(a, memory[i])
451 b = add32(b, memory[i + 1])
452 c = add32(c, memory[i + 2])
453 d = add32(d, memory[i + 3])
454 e = add32(e, memory[i + 4])
455 f = add32(f, memory[i + 5])
456 g = add32(g, memory[i + 6])
457 h = add32(h, memory[i + 7])
458
459 mix()
460
461 // Fill in the memory with messy stuff (again)
462 memory[i] = a
463 memory[i + 1] = b
464 memory[i + 2] = c
465 memory[i + 3] = d
466 memory[i + 4] = e
467 memory[i + 5] = f
468 memory[i + 6] = g
469 memory[i + 7] = h
470 }
471
472 pnrg()
473
474 generation = 256
475 }
476
477 function pnrg(n?: number): void {
478 let i = 0
479 let x = 0
480 let y = 0
481
482 n = Predicate.isUndefined(n) ? 1 : Math.abs(Math.floor(n))
483
484 while (n--) {
485 counter = add32(counter, 1)
486 lastResult = add32(lastResult, counter)
487
488 for (i = 0; i < 256; i++) {
489 switch (i & 3) {
490 case 0: {
491 accumulator ^= accumulator << 13
492 break
493 }
494 case 1: {
495 accumulator ^= accumulator >>> 6
496 break
497 }
498 case 2: {
499 accumulator ^= accumulator << 2
500 break
501 }
502 case 3: {
503 accumulator ^= accumulator >>> 16
504 break
505 }
506 }
507
508 accumulator = add32(memory[(i + 128) & 0xff], accumulator)
509 x = memory[i]
510
511 memory[i] = add32(memory[(x >>> 2) & 0xff], add32(accumulator, lastResult))
512 y = memory[i]
513
514 result[i] = add32(memory[(y >>> 10) & 0xff], x)
515 lastResult = result[i]
516 }
517 }
518 }
519
520 /**
521 * Returns a signed, random integer in the range [-2^31, 2^31).
522 */
523 function nextInt32(): number {
524 if (!generation--) {
525 pnrg()
526 generation = 255
527 }
528 return result[generation]
529 }
530
531 function nextIntUnsafe(): number {
532 return Math.floor(nextDoubleUnsafe() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) +
533 Number.MIN_SAFE_INTEGER
534 }
535
536 /**
537 * Returns a 53-bit fraction in the range [0, 1).
538 */
539 function nextDoubleUnsafe(): number {
540 const hi = (nextInt32() >>> 0) & 0x1FFFFF // take top 21 bits
541 const lo = nextInt32() >>> 0 // full 32 bits
542
543 // 53-bit integer
544 const combined = hi * 4294967296 + lo
545
546 return combined / 0x20000000000000 // [0, 1)
547 }
548
549 return { nextIntUnsafe, nextDoubleUnsafe }
550}
551
552/**
553 * 32-bit addition with overflow handling (JavaScript numbers are 53-bit).
554 *
555 * Example: add32(0xFFFFFFFF, 0x00000001) = 0x00000000 (wraps around)
556 */
557function add32(x: number, y: number): number {
558 // Add lower 16 bits separately to handle carry
559 // Example: x=0x12345678, y=0xABCDEF01
560 // lsb = (0x5678 + 0xEF01) = 0x14579
561 const lsb = (x & 0xffff) + (y & 0xffff)
562
563 // Add upper 16 bits + carry from lower addition
564 // msb = (0x1234 + 0xABCD + (0x14579 >>> 16)) = (0x1234 + 0xABCD + 0x1) = 0xBE02
565 const msb = (x >>> 16) + (y >>> 16) + (lsb >>> 16)
566
567 // Combine: upper 16 bits | lower 16 bits (masked to prevent double carry)
568 // return (0xBE02 << 16) | (0x14579 & 0xffff) = 0xBE024579
569 return (msb << 16) | (lsb & 0xffff)
570}
571
572const seedEncoder = new TextEncoder()
573
574/**
575 * Convert a string to UTF-8 encoded 32-bit integers (little-endian).
576 */
577function toIntArray(seed: string): Array<number> {
578 const bytes = seedEncoder.encode(seed)
579 const result: Array<number> = []
580
581 for (let index = 0; index < bytes.length; index += 4) {
582 result.push(
583 ((bytes[index] ?? 0) << 0) |
584 ((bytes[index + 1] ?? 0) << 8) |
585 ((bytes[index + 2] ?? 0) << 16) |
586 ((bytes[index + 3] ?? 0) << 24)
587 )
588 }
589
590 return result
591}