From: Jérôme Benoit Date: Mon, 24 Oct 2022 13:40:53 +0000 (+0200) Subject: Move random generator inputs check at the right place X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;ds=sidebyside;h=aa418e7875a766560efdb187c86052df0d1df250;hp=47006ddf6055b02dd084ae91269f12b44ce8225d;p=benchmarks-js.git Move random generator inputs check at the right place Signed-off-by: Jérôme Benoit --- diff --git a/benchmark-utils.js b/benchmark-utils.js index 678a2b3..35b47f9 100644 --- a/benchmark-utils.js +++ b/benchmark-utils.js @@ -15,20 +15,33 @@ function secureRandom () { * @returns */ function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { - if (max < 0) { + if (max < min || max < 0 || min < 0) { throw new RangeError('Invalid interval') } max = Math.floor(max) if (min != null && min !== 0) { - if (max < min || min < 0) { - throw new RangeError('Invalid interval') - } min = Math.ceil(min) return Math.floor(secureRandom() * (max - min + 1)) + min } return Math.floor(secureRandom() * (max + 1)) } +/** + * + * @param max + * @param min + * @param negative + * @returns + */ +function generateRandomFloat (max = Number.MAX_VALUE, min = 0, negative = true) { + if (max < min || max < 0 || min < 0) { + throw new RangeError('Invalid interval') + } + const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff + const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1 + return sign * (randomPositiveFloat * (max - min) + min) +} + /** * * @param size @@ -48,22 +61,6 @@ function generateRandomNumberArray ( return array } -/** - * - * @param max - * @param min - * @param negative - * @returns - */ -function generateRandomFloat (max = Number.MAX_VALUE, min = 0, negative = true) { - if (max < min || min < 0 || max < 0) { - throw new RangeError('Invalid interval') - } - const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff - const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1 - return sign * (randomPositiveFloat * (max - min) + min) -} - /** * @param ms * @returns