[backend][nodejs] Add seed to random decision
This commit is contained in:
@@ -14,6 +14,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"random": "^3.0.3",
|
||||
"seedrandom": "^3.0.5",
|
||||
"should": "^13.2.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const random = require('random');
|
||||
const seedrandom = require("seedrandom");
|
||||
|
||||
class Choice {
|
||||
constructor(name) {
|
||||
@@ -16,7 +17,8 @@ const choices = [
|
||||
new Choice('C')
|
||||
];
|
||||
|
||||
exports.getRandomChoice = () => {
|
||||
exports.getRandomChoice = (seed = new Date()) => {
|
||||
random.use(seedrandom(seed));
|
||||
return choices[random.int(0, choices.length - 1)];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ const should = require('should');
|
||||
const randomDecision = require('../random-decision');
|
||||
|
||||
describe('randomDecision', function () {
|
||||
describe('#getRandomChoice', function () {
|
||||
describe('#getRandomChoice()', function () {
|
||||
it(`should return one of available choices`, function () {
|
||||
randomDecision.getRandomChoice().should.equalOneOf(randomDecision.choices);
|
||||
});
|
||||
@@ -35,4 +35,14 @@ describe('randomDecision', function () {
|
||||
should.fail(selectedChoices, expectedChoice, 'Last choice was never selected');
|
||||
})
|
||||
})
|
||||
describe('#getRandomChoice(seed)', function () {
|
||||
it('should always select the same value when the seed is the same', function () {
|
||||
const seed = new Date();
|
||||
const initialDecision = randomDecision.getRandomChoice(seed);
|
||||
for (let i = 0; i <= 1000; i++) {
|
||||
let randomChoice = randomDecision.getRandomChoice(seed);
|
||||
assert.strictEqual(randomChoice, initialDecision);
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user