A Better RandRange()
by Ryan Guill
Every CFML engine I can find - Adobe ColdFusion 10, 11 and 2016, Lucee 4.5 and 5 - has a bug where if you try to use randRange()
on 231-1 (MAX_INT
) it will overflow and give you a negative number. See for yourself: http://trycf.com/gist/726e96e5c5e9498b32a2/acf2016. Here is a better way that supports not only MAX_INT
but also MAX_LONG
(263-1).
<cfscript>
function randRangeInt (min, max) {
return createObject("java", "java.util.concurrent.ThreadLocalRandom").current().nextInt(min, max);
}
function randRangeLong (min, max) {
return createObject("java", "java.util.concurrent.ThreadLocalRandom").current().nextLong(min, max);
}
//old and busted
writedump(randRange(0, 2147483647)); //negative!
writedump(randRange(0, 2^31-1)); //negative!
//the new hotness
writedump(randRangeInt(0, 2147483647));
writedump(randRangeInt(0, 2^31-1));
writedump(randRangeInt(0, 2147483646));
writedump(randRangeInt(0, 2^31-2));
writedump(randRangeLong(0, 9223372036854775808));
writedump(randRangeLong(0, 2^63-1));
</cfscript>
Note: this requires java 1.7+. Relevant bugs in ACF (closed of course) and Lucee. Both are over a year old.
Subscribe via RSS