import * as Chunk from "@effect/data/Chunk" import * as Context from "@effect/data/Context" import { pipe } from "@effect/data/Function" import * as PCGRandom from "@effect/data/PCGRandom" import type * as Effect from "@effect/io/Effect" import * as core from "@effect/io/internal/core" import type * as Random from "@effect/io/Random" /** @internal */ const RandomSymbolKey = "@effect/io/Random" /** @internal */ export const RandomTypeId: Random.RandomTypeId = Symbol.for( RandomSymbolKey ) as Random.RandomTypeId /** @internal */ export const randomTag: Context.Tag = Context.Tag(RandomTypeId) /** @internal */ class RandomImpl implements Random.Random { readonly [RandomTypeId]: Random.RandomTypeId = RandomTypeId readonly PRNG: PCGRandom.PCGRandom constructor(readonly seed: number) { this.PRNG = new PCGRandom.PCGRandom(seed) } next(): Effect.Effect { return core.sync(() => this.PRNG.number()) } nextBoolean(): Effect.Effect { return core.map(this.next(), (n) => n > 0.5) } nextInt(): Effect.Effect { return core.sync(() => this.PRNG.integer(Number.MAX_SAFE_INTEGER)) } nextRange(min: number, max: number): Effect.Effect { return core.map(this.next(), (n) => (max - min) * n + min) } nextIntBetween(min: number, max: number): Effect.Effect { return core.sync(() => this.PRNG.integer(max - min) + min) } shuffle(elements: Iterable): Effect.Effect> { return shuffleWith(elements, (n) => this.nextIntBetween(0, n + 1)) } } const shuffleWith = ( elements: Iterable, nextIntBounded: (n: number) => Effect.Effect ): Effect.Effect> => { return core.suspend(() => pipe( core.sync(() => Array.from(elements)), core.flatMap((buffer) => { const numbers: Array = [] for (let i = buffer.length; i >= 2; i = i - 1) { numbers.push(i) } return pipe( numbers, core.forEachSequentialDiscard((n) => pipe( nextIntBounded(n), core.map((k) => swap(buffer, n - 1, k)) ) ), core.as(Chunk.fromIterable(buffer)) ) }) ) ) } const swap = (buffer: Array, index1: number, index2: number): Array => { const tmp = buffer[index1]! buffer[index1] = buffer[index2]! buffer[index2] = tmp return buffer } export const make = (seed: number): Random.Random => new RandomImpl(seed)