Skip to content

Commit 79dae1b

Browse files
committed
Improve randomness of array shuffling
1 parent dc1581e commit 79dae1b

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

web-src/app.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,29 @@ let bgDivs = []
5454

5555
const wrapper = document.getElementById('bg');
5656

57-
backgrounds.sort(() => Math.random() - 0.5);
57+
// Shuffle the array of backgrounds.
58+
let currentIndex = backgrounds.length;
59+
60+
// While there remain elements to shuffle...
61+
while (currentIndex != 0) {
62+
63+
// Pick a remaining element...
64+
let randomIndex = Math.floor(Math.random() * currentIndex);
65+
currentIndex--;
66+
67+
// And swap it with the current element.
68+
[backgrounds[currentIndex], backgrounds[randomIndex]] = [
69+
backgrounds[randomIndex], backgrounds[currentIndex]];
70+
}
71+
72+
let numberOfBackgrounds = 5
5873

5974
if (!('connection' in navigator) || navigator.connection.saveData) {
60-
backgrounds = backgrounds.slice(0, 3)
75+
numberOfBackgrounds = 3
6176
}
6277

78+
backgrounds = backgrounds.slice(0, numberOfBackgrounds)
79+
6380
const avif = await supportsAvif;
6481
const webp = await supportsWebp;
6582

0 commit comments

Comments
 (0)