| 1 | const Benchmark = require('benny') |
| 2 | const { secureRandom } = require('./benchmark-utils') |
| 3 | |
| 4 | const maximum = Number.MAX_SAFE_INTEGER |
| 5 | |
| 6 | /** |
| 7 | * @param max |
| 8 | * @param min |
| 9 | * @returns |
| 10 | */ |
| 11 | function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { |
| 12 | max = Math.floor(max) |
| 13 | if (min) { |
| 14 | min = Math.ceil(min) |
| 15 | return Math.floor(secureRandom() * (max - min + 1)) + min |
| 16 | } |
| 17 | return Math.floor(secureRandom() * (max + 1)) |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * @param max |
| 22 | * @param min |
| 23 | * @returns |
| 24 | */ |
| 25 | function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { |
| 26 | max = Math.floor(max) |
| 27 | if (min) { |
| 28 | min = Math.ceil(min) |
| 29 | return Math.floor(Math.random() * (max - min + 1)) + min |
| 30 | } |
| 31 | return Math.floor(Math.random() * (max + 1)) |
| 32 | } |
| 33 | |
| 34 | Benchmark.suite( |
| 35 | 'Random Integer Generator', |
| 36 | Benchmark.add('Secure random integer generator', function () { |
| 37 | getSecureRandomInteger(maximum) |
| 38 | }), |
| 39 | Benchmark.add('Random integer generator', function () { |
| 40 | getRandomInteger(maximum) |
| 41 | }), |
| 42 | Benchmark.cycle(), |
| 43 | Benchmark.complete(), |
| 44 | Benchmark.save({ file: 'random-integer-generator', format: 'chart.html' }), |
| 45 | Benchmark.save({ file: 'random-integer-generator', format: 'table.html' }) |
| 46 | ) |