From 9fcc9ca59b8c6dd3508c910f7c0791490b6c8d94 Mon Sep 17 00:00:00 2001 From: Oli Lalonde Date: Sun, 2 Aug 2020 08:08:39 -0400 Subject: [PATCH] crypto: add randomInt function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: /~https://github.com/nodejs/node/pull/34600 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis Reviewed-By: Tobias Nießen --- doc/api/crypto.md | 39 ++++++ lib/crypto.js | 4 +- lib/internal/crypto/random.js | 80 ++++++++++++- test/parallel/test-crypto-random.js | 180 ++++++++++++++++++++++++++++ 4 files changed, 301 insertions(+), 2 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 539ce6fc79de46..f0c7620c10dbcf 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -2801,6 +2801,44 @@ threadpool request. To minimize threadpool task length variation, partition large `randomFill` requests when doing so as part of fulfilling a client request. +### `crypto.randomInt([min, ]max[, callback])` + + +* `min` {integer} Start of random range (inclusive). **Default**: `0`. +* `max` {integer} End of random range (exclusive). +* `callback` {Function} `function(err, n) {}`. + +Return a random integer `n` such that `min <= n < max`. This +implementation avoids [modulo bias][]. + +The range (`max - min`) must be less than `2^48`. `min` and `max` must +be safe integers. + +If the `callback` function is not provided, the random integer is +generated synchronously. + +```js +// Asynchronous +crypto.randomInt(3, (err, n) => { + if (err) throw err; + console.log(`Random number chosen from (0, 1, 2): ${n}`); +}); +``` + +```js +// Synchronous +const n = crypto.randomInt(3); +console.log(`Random number chosen from (0, 1, 2): ${n}`); +``` + +```js +// With `min` argument +const n = crypto.randomInt(1, 7); +console.log(`The dice rolled: ${n}`); +``` + ### `crypto.scrypt(password, salt, keylen[, options], callback)`