From 37119b9d1a77eb73f2825c7394d8f9e3bdaf189e Mon Sep 17 00:00:00 2001 From: Julien Calixte Date: Mon, 24 Jul 2023 22:45:02 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20(shuffle)=20better=20shuffle=20a?= =?UTF-8?q?rray?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index d27c65c..baa8b8c 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,14 +1,17 @@ export const shuffleArray = (array: T[]) => { - const arrayCopy = [...array] + let currentIndex = array.length, + randomIndex - for (let i = array.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)) - const temp = array[i] - array[i] = array[j] - array[j] = temp + while (currentIndex !== 0) { + randomIndex = Math.floor(Math.random() * currentIndex) + currentIndex-- + ;[array[currentIndex], array[randomIndex]] = [ + array[randomIndex], + array[currentIndex] + ] } - return arrayCopy + return array } export const popNElement = (array: T[], numberOfElements: number) => {