[backend][nodejs] Add seed to random decision

This commit is contained in:
koeberlue
2021-04-05 20:49:54 +02:00
parent 45b39fea22
commit 4a839343f5
3 changed files with 15 additions and 2 deletions

View File

@@ -14,6 +14,7 @@
}, },
"dependencies": { "dependencies": {
"random": "^3.0.3", "random": "^3.0.3",
"seedrandom": "^3.0.5",
"should": "^13.2.3" "should": "^13.2.3"
} }
} }

View File

@@ -1,4 +1,5 @@
const random = require('random'); const random = require('random');
const seedrandom = require("seedrandom");
class Choice { class Choice {
constructor(name) { constructor(name) {
@@ -16,7 +17,8 @@ const choices = [
new Choice('C') new Choice('C')
]; ];
exports.getRandomChoice = () => { exports.getRandomChoice = (seed = new Date()) => {
random.use(seedrandom(seed));
return choices[random.int(0, choices.length - 1)]; return choices[random.int(0, choices.length - 1)];
} }

View File

@@ -3,7 +3,7 @@ const should = require('should');
const randomDecision = require('../random-decision'); const randomDecision = require('../random-decision');
describe('randomDecision', function () { describe('randomDecision', function () {
describe('#getRandomChoice', function () { describe('#getRandomChoice()', function () {
it(`should return one of available choices`, function () { it(`should return one of available choices`, function () {
randomDecision.getRandomChoice().should.equalOneOf(randomDecision.choices); randomDecision.getRandomChoice().should.equalOneOf(randomDecision.choices);
}); });
@@ -35,4 +35,14 @@ describe('randomDecision', function () {
should.fail(selectedChoices, expectedChoice, 'Last choice was never selected'); 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);
}
})
})
}) })