fix: JS random int block with non-ints.

Previously random_int(2.4, 2.6) would return 2.  This is wrong.  NaN is better; it's the same as random_int("hello", []).

Python, Lua, PHP all have their own native functions for random int, so we just use their native behaviours.  Dart is another matter (separate PR).

I think making this block more accurate is worth the code given that a LOT of kids use "random integer" for stuff.

Also re-flow the Math test blocks, they were overlapping.
And the Dart interpreter link has changed URLs.
This commit is contained in:
Neil Fraser
2023-12-08 23:52:44 +01:00
parent f7e6f5cfb1
commit e950b8de47
4 changed files with 39 additions and 23 deletions

View File

@@ -414,12 +414,20 @@ export function math_random_int(
'mathRandomInt',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(a, b) {
a = Number(a);
b = Number(b);
if (a > b) {
// Swap a and b to ensure a is smaller.
var c = a;
a = b;
b = c;
}
a = Math.ceil(a);
b = Math.floor(b);
if (a > b) {
// No integers between the inputs (e.g. 2.4 & 2.6).
return NaN;
}
return Math.floor(Math.random() * (b - a + 1) + a);
}
`,