word/quiz: fisher-yates shuffle algorithm
authorMischa POSLAWSKY <perl@shiar.org>
Wed, 29 Dec 2021 05:04:34 +0000 (06:04 +0100)
committerMischa POSLAWSKY <perl@shiar.org>
Fri, 31 Dec 2021 04:29:05 +0000 (05:29 +0100)
Fixes very bad randomisation in some browsers.

Reference: <https://javascript.info/array-methods#shuffle-an-array>

word/quiz.js

index 70f8500bf2bffa30e0b5b899be79c3d561effc92..361d075e66391f517b08b8f51f7a12222ef9b954 100644 (file)
@@ -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 {