shuffleArr
Shuffles the elements of an array using Fisher-Yates algorithm.
1./**2.* Shuffles the elements of an array using Fisher-Yates algorithm.3.**/4.const shuffleArr = <T,>(arr: T[]) => {5.const copy = [...arr];6.for (let i = copy.length - 1; i > 0; i--) {7.const j = Math.floor(Math.random() * (i + 1));8.[copy[i], copy[j]] = [copy[j], copy[i]];9.}10.11.return copy;12.};13.14.export default shuffleArr;
1. Installtion
npx @jrtilak/lazykit add shuffleArr
2. Parameters
arr
(T[]
)
The array to be shuffled. The function creates a copy of this array before shuffling to maintain the original order.
3. Returns
T[]
Returns a new array with the elements shuffled randomly. The original array remains unchanged.
4. Type Parameters
T
The type of elements in the array. This allows the function to work with arrays of any type, ensuring type safety for the shuffled elements.
5. Usage
1.import shuffleArr from "@/helpers/shuffleArr";2.3.const arr = [1, 2, 3, 4, 5];4.const shuffledArr = shuffleArr(arr);5.console.log(shuffledArr);6.// Expected output: shuffled array of given array