X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=benchmark-utils.js;h=841cef87a6a9bc32bac9fa2bd161b76870050e3f;hb=da8d42f6bee8d0ff2a0f1b5b3e1b8cdc82b57ad1;hp=4de6ea7728d45765c65573991495c9fb3979f374;hpb=a9c78d5d3394dce4eccd9f244c88879666cba677;p=benchmarks-js.git diff --git a/benchmark-utils.js b/benchmark-utils.js index 4de6ea7..841cef8 100644 --- a/benchmark-utils.js +++ b/benchmark-utils.js @@ -1,12 +1,31 @@ +const crypto = require('crypto') + +/** + * Generate a cryptographically secure random number in the [0,1[ range + * + * @returns + */ +function secureRandom () { + return crypto.randomBytes(4).readUInt32LE() / 0x100000000 +} + /** * @param max * @param min */ function generateRandomInteger (max, min = 0) { + if (max < 0) { + throw new RangeError('Invalid interval') + } + max = Math.floor(max) if (min) { - return Math.floor(Math.random() * (max - min + 1) + min) + 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(Math.random() * max + 1) + return Math.floor(secureRandom() * (max + 1)) } /** @@ -21,4 +40,4 @@ const LIST_FORMATTER = new Intl.ListFormat('en-US', { type: 'conjunction' }) -module.exports = { generateRandomInteger, sleep, LIST_FORMATTER } +module.exports = { generateRandomInteger, sleep, secureRandom, LIST_FORMATTER }