From 26074080358f5993e59f19526704c58c1de2606f Mon Sep 17 00:00:00 2001 From: Mischa POSLAWSKY Date: Wed, 29 Dec 2021 06:04:34 +0100 Subject: [PATCH] word/quiz: fisher-yates shuffle algorithm Fixes very bad randomisation in some browsers. Reference: --- word/quiz.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/word/quiz.js b/word/quiz.js index 70f8500..361d075 100644 --- a/word/quiz.js +++ b/word/quiz.js @@ -1,5 +1,9 @@ Array.prototype.shuffle = function () { - return this.sort(() => {return .5 - Math.random()}); + for (let i = this.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); // random index 0..i + [this[i], this[j]] = [this[j], this[i]]; // swap elements + } + return this; }; class WordQuiz { -- 2.30.0