Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/modules/Random.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Added in v2.0.0

- [utils](#utils)
- [random](#random)
- [randomArrayElem](#randomarrayelem)
- [randomBool](#randombool)
- [randomElem](#randomelem)
- [randomInt](#randomint)
Expand All @@ -36,6 +37,18 @@ export declare const random: IO<number>

Added in v2.0.0

## randomArrayElem

Returns a random element of a `ReadonlyArray`.

**Signature**

```ts
export declare const randomArrayElem: <A>(as: readonly A[]) => IOOption<A>
```

Added in v2.13.2

## randomBool

Returns a random boolean value with an equal chance of being `true` or `false`
Expand Down
15 changes: 14 additions & 1 deletion src/Random.ts
Original file line number Diff line number Diff line change
@@ -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'

/**
Expand Down Expand Up @@ -60,3 +62,14 @@ export const randomElem = <A>(as: ReadonlyNonEmptyArray<A>): IO<A> =>
randomInt(0, as.length - 1),
map((i) => as[i])
)

/**
* Returns a random element of a `ReadonlyArray`.
*
* @since 2.13.2
*/
export const randomArrayElem = <A>(as: ReadonlyArray<A>): IOOption<A> =>
pipe(
as,
match(() => none, flow(randomElem, fromIO))
)
9 changes: 8 additions & 1 deletion test/Random.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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)
})
})