From 7eaf12120ddecf54d7d2236be8e393382d318871 Mon Sep 17 00:00:00 2001 From: plucisano Date: Tue, 20 Dec 2022 12:05:17 +0100 Subject: [PATCH] Add randomArrayElem --- docs/modules/Random.ts.md | 13 +++++++++++++ src/Random.ts | 15 ++++++++++++++- test/Random.ts | 9 ++++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/docs/modules/Random.ts.md b/docs/modules/Random.ts.md index 3dcc52e3be..428b459815 100644 --- a/docs/modules/Random.ts.md +++ b/docs/modules/Random.ts.md @@ -14,6 +14,7 @@ Added in v2.0.0 - [utils](#utils) - [random](#random) + - [randomArrayElem](#randomarrayelem) - [randomBool](#randombool) - [randomElem](#randomelem) - [randomInt](#randomint) @@ -36,6 +37,18 @@ export declare const random: IO Added in v2.0.0 +## randomArrayElem + +Returns a random element of a `ReadonlyArray`. + +**Signature** + +```ts +export declare const randomArrayElem: (as: readonly A[]) => IOOption +``` + +Added in v2.13.2 + ## randomBool Returns a random boolean value with an equal chance of being `true` or `false` diff --git a/src/Random.ts b/src/Random.ts index 3addd642ae..3b1fefa188 100644 --- a/src/Random.ts +++ b/src/Random.ts @@ -1,8 +1,10 @@ /** * @since 2.0.0 */ +import { flow, pipe } from './function' import { IO, map } from './IO' -import { pipe } from './function' +import { fromIO, IOOption, none } from './IOOption' +import { match } from './ReadonlyArray' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' /** @@ -60,3 +62,14 @@ export const randomElem = (as: ReadonlyNonEmptyArray): IO => randomInt(0, as.length - 1), map((i) => as[i]) ) + +/** + * Returns a random element of a `ReadonlyArray`. + * + * @since 2.13.2 + */ +export const randomArrayElem = (as: ReadonlyArray): IOOption => + pipe( + as, + match(() => none, flow(randomElem, fromIO)) + ) diff --git a/test/Random.ts b/test/Random.ts index 6309fbdfd6..515cb90947 100644 --- a/test/Random.ts +++ b/test/Random.ts @@ -1,5 +1,6 @@ -import * as U from './util' +import { isSome, none } from '../src/Option' import * as _ from '../src/Random' +import * as U from './util' describe('Random', () => { it('random', () => { @@ -33,4 +34,10 @@ describe('Random', () => { const e = _.randomElem([1, 2, 3])() U.deepStrictEqual(e >= 1 && e <= 3, true) }) + + it('randomArrayElem', () => { + const eOption = _.randomArrayElem([1, 2, 3])() + U.deepStrictEqual(_.randomArrayElem([])(), none) + U.deepStrictEqual(isSome(eOption) && eOption.value >= 1 && eOption.value <= 3, true) + }) })