diff --git a/docs/random/shuffle.mdx b/docs/random/shuffle.mdx index 8b37d82f..7ccd90b0 100644 --- a/docs/random/shuffle.mdx +++ b/docs/random/shuffle.mdx @@ -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' @@ -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) +``` diff --git a/src/random/shuffle.ts b/src/random/shuffle.ts index 79d2bc99..bf0b8ea0 100644 --- a/src/random/shuffle.ts +++ b/src/random/shuffle.ts @@ -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 @@ -15,7 +17,24 @@ import * as _ from 'radashi' * @version 12.1.0 */ export function shuffle( + /** + * 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()