mirror of
https://github.com/google/blockly.git
synced 2026-02-17 13:00:10 +01:00
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:
@@ -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);
|
||||
}
|
||||
`,
|
||||
|
||||
Reference in New Issue
Block a user