developmentseed / bioacoustics-frontend

Frontend code for the Google Bioacoustics project that's used by A2O Search
https://search.acousticobservatory.org/
MIT License
1 stars 0 forks source link

fix: Remove -1 from randomiser #155

Closed oliverroick closed 11 months ago

oliverroick commented 11 months ago

Fix #154

I believe the culprit is this line:

const index = Math.floor(Math.random() * recordings.length - 1);

For twenty years now, I believed Math.random() returns a number between 0 and 1 inclusive, but that's not the case (emphasis mine):

The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1

So in cases when Math.random() returns a number < 0.2, index results in -1. -1 used to get an element from an array returns undefined, unless you have previously set the value (like someArray[-1] = "some value").

And we're not going to talk about the fact that I forgot basic math; the line above should have read:

const index = Math.floor(Math.random() * (recordings.length - 1));

I also turned the "I'm feeling lucky" link into a NextLink so the page is preloaded.