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.
Fix #154
I believe the culprit is this line:
For twenty years now, I believed
Math.random()
returns a number between 0 and 1 inclusive, but that's not the case (emphasis mine):So in cases when
Math.random()
returns a number < 0.2,index
results in-1
.-1
used to get an element from an array returnsundefined
, unless you have previously set the value (likesomeArray[-1] = "some value"
).And we're not going to talk about the fact that I forgot basic math; the line above should have read:
I also turned the "I'm feeling lucky" link into a
NextLink
so the page is preloaded.