Skip to content

Commit

Permalink
docs(shuffle): mention custom RNG function + link to Fisher-Yates alg…
Browse files Browse the repository at this point in the history
…orithm (#318)
  • Loading branch information
MarlonPassos-git authored Jan 5, 2025
1 parent 6cac3dd commit 50c3c83
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
11 changes: 10 additions & 1 deletion docs/random/shuffle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ since: 12.1.0

### Usage

Create a new array with the items of the given array but in a random order. The randomization is done using the Fisher-Yates algorithm, which is mathematically proven to be unbiased (i.e. all permutations are equally likely).
Create a new array with the items of the given array but in a random order. The randomization is done using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), which is mathematically proven to be unbiased (i.e. all permutations are equally likely).

```ts
import * as _ from 'radashi'
Expand All @@ -31,3 +31,12 @@ const fish = [

_.shuffle(fish)
```

You can provide a custom random function to make the shuffle more or less random. The custom random function takes minimum and maximum values and returns a random number between them.

```ts
const array = [1, 2, 3, 4, 5]
const customRandom = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min
_.shuffle(array, customRandom)
```
21 changes: 20 additions & 1 deletion src/random/shuffle.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as _ from 'radashi'

/**
* Clone an array and shuffle its items randomly.
* Create a new array with the items of the given array but in a random order.
* The randomization is done using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle),
* which is mathematically proven to be unbiased (i.e. all permutations are equally likely).
*
* @see https://radashi.js.org/reference/random/shuffle
* @example
Expand All @@ -15,7 +17,24 @@ import * as _ from 'radashi'
* @version 12.1.0
*/
export function shuffle<T>(
/**
* The array to shuffle.
*/
array: readonly T[],
/**
* You can provide a custom random function to make the shuffle more or less
* random. The custom random function takes minimum and maximum values and
* returns a random number between them.
*
* @default _.random
* @example
*
* ```ts
* const array = [1, 2, 3, 4, 5]
* const customRandom = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
* _.shuffle(array, customRandom)
* ```
*/
random: (min: number, max: number) => number = _.random,
): T[] {
const newArray = array.slice()
Expand Down

0 comments on commit 50c3c83

Please sign in to comment.