typedash
Version:
modern, type-safe collection of utility functions
26 lines (25 loc) • 726 B
JavaScript
//#region src/functions/shuffle/shuffle.ts
/**
* Returns a new array with elements randomly reordered using the Fisher-Yates algorithm.
* Does not mutate the input array.
* @param array The array to shuffle.
* @returns A new array with the same elements in a random order.
* @example
* ```ts
* shuffle([1, 2, 3, 4]) // e.g. [3, 1, 4, 2]
* shuffle([]) // []
* shuffle(null) // []
* shuffle(undefined) // []
* ```
*/
function shuffle(array) {
const result = [...array ?? []];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
//#endregion
export { shuffle as t };
//# sourceMappingURL=shuffle-CDB_o23Z.js.map