-
Notifications
You must be signed in to change notification settings - Fork 340
/
handler.js
43 lines (33 loc) · 1.12 KB
/
handler.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
const jokes = require('./jokes/index.json');
let lastJokeId = 0;
jokes.forEach(jk => jk.id = ++lastJokeId);
const randomJoke = () => {
return jokes[Math.floor(Math.random() * jokes.length)];
}
/**
* Get N random jokes from a jokeArray
*/
const randomN = (jokeArray, n) => {
const limit = jokeArray.length < n ? jokeArray.length : n;
const randomIndicesSet = new Set();
while (randomIndicesSet.size < limit) {
const randomIndex = Math.floor(Math.random() * jokeArray.length);
if (!randomIndicesSet.has(randomIndex)) {
randomIndicesSet.add(randomIndex);
}
}
return Array.from(randomIndicesSet).map(randomIndex => {
return jokeArray[randomIndex];
});
};
const randomTen = () => randomN(jokes, 10);
const randomSelect = (number) => randomN(jokes, number);
const jokeByType = (type, n) => {
return randomN(jokes.filter(joke => joke.type === type), n);
};
/**
* @param {Number} id - joke id
* @returns a single joke object or undefined
*/
const jokeById = (id) => (jokes.filter(jk => jk.id === id)[0]);
module.exports = { jokes, randomJoke, randomN, randomTen, randomSelect, jokeById, jokeByType };