Skip to content

Commit

Permalink
Optimized fetch of random values using cache (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
TanukiSharp authored and brendanashworth committed Jun 16, 2019
1 parent 75032c4 commit ea64255
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,29 @@ var crypto = require('crypto');

var self = module.exports;

const RANDOM_BATCH_SIZE = 256;

var randomIndex;
var randomBytes;

var getNextRandomValue = function() {
if (randomIndex === undefined || randomIndex >= randomBytes.length) {
randomIndex = 0;
randomBytes = crypto.randomBytes(RANDOM_BATCH_SIZE);
}

var result = randomBytes[randomIndex];
randomIndex += 1;

return result;
};

// Generates a random number
var randomNumber = function(max) {
// gives a number between 0 (inclusive) and max (exclusive)
var rand = crypto.randomBytes(1)[0];
var rand = getNextRandomValue();
while (rand >= 256 - (256 % max)) {
rand = crypto.randomBytes(1)[0];
rand = getNextRandomValue();
}
return rand % max;
};
Expand Down

0 comments on commit ea64255

Please sign in to comment.