Skip to content

Commit

Permalink
Update Random to create a per-instance copy of the RNG
Browse files Browse the repository at this point in the history
Before this change, it appeared that multiple, independent Faker
instances were legal.  But, when multiple instances were created, their
shared random number generators would overwrite each others' states.

After this change, each Random instance (and therefore each Faker
instance) has its own copy of the random number generator, ensuring that
calls to one Faker instance do not affect the stream of values generated
by another.
  • Loading branch information
chris-chambers authored and Marak committed Sep 8, 2017
1 parent 2ea9730 commit 8a33cf0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,27 @@ var mersenne = require('../vendor/mersenne');
* @namespace faker.random
*/
function Random (faker, seed) {
var gen = new mersenne.MersenneTwister19937();

// Use a user provided seed if it exists
if (seed) {
if (Array.isArray(seed) && seed.length) {
mersenne.seed_array(seed);
gen.init_by_array(seed);
}
else {
mersenne.seed(seed);
gen.init_genrand(seed);
}
}

// Copied from the marsenne package for compatibility.
function rand(max, min) {
if (max === undefined) {
min = 0;
max = 32768;
}
return Math.floor(gen.genrand_real2() * (max - min) + min);
}

/**
* returns a single random number based on a max number or range
*
Expand Down Expand Up @@ -48,7 +60,7 @@ function Random (faker, seed) {
}

var randomNumber = Math.floor(
mersenne.rand(max / options.precision, options.min / options.precision));
rand(max / options.precision, options.min / options.precision));
// Workaround problem in Float point arithmetics for e.g. 6681493 / 0.01
randomNumber = randomNumber / (1 / options.precision);

Expand Down
16 changes: 16 additions & 0 deletions test/random.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ if (typeof module !== 'undefined') {
var sinon = require('sinon');
var _ = require('lodash');
var faker = require('../index');
var Faker = require('../lib');
}


Expand Down Expand Up @@ -189,4 +190,19 @@ describe("random.js", function () {
assert.ok(hex.match(/^(0x)[0-9a-f]+$/i));
})
})

describe('independent', function() {

it('generates independent sequences', function () {
var faker1 = new Faker();
faker1.seed(1);

var faker2 = new Faker();
faker2.seed(1);

assert.equal(faker1.random.number(), faker2.random.number());
})

})

});

0 comments on commit 8a33cf0

Please sign in to comment.