-
Notifications
You must be signed in to change notification settings - Fork 2
/
random-choice.js
52 lines (43 loc) · 1.25 KB
/
random-choice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* This file randomly chooses an id from the local database in a json file, and uses it
* if it has not been seen before.
* To execute :
* node random-choice.js
*
* Authors : Corentin Forler, Pierre Sibut-Bourde, 2021.
*/
/**
* Practical requirements.
*/
const { RedisClient } = require('./redis-client');
/**
* @param {Array} array
* @returns {any}
*/
function pickRandom(array) {
const index = Math.floor(Math.random() * array.length);
return array[index];
}
/**
* Functions that returns a random element from the ids.
* @returns {number | undefined}
*/
async function randomChoice(readOnly = false) {
const redisClient = await RedisClient();
const allIds = JSON.parse((await redisClient.get('all-ids')) || '[]');
const usedIds = JSON.parse((await redisClient.get('used-ids')) || '[]');
const nonUsedIds = allIds.filter(x => !usedIds.includes(x));
if (nonUsedIds.length === 0) {
return;
}
// Pick a random non-used id
const randomId = pickRandom(nonUsedIds);
// Update the list of used ids
if (readOnly) {
usedIds.push(randomId);
await redisClient.set('used-ids', JSON.stringify(usedIds)); // await that writing is done in the DB.
}
redisClient.quit();
return randomId;
}
module.exports = { randomChoice };