-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (40 loc) · 1.36 KB
/
index.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
const sentences = require("./sentences.json");
const totalSentencesCount = sentences.length;
const totalDigits = String(totalSentencesCount).length;
// console.log(typeof sentences, Array.isArray(sentences), sentences);
class RandomSentences {
#recentIndices = [];
#getRandomIndex() {
const randomNumber = Math.random();
const randomNumberMultiplied = randomNumber * 10 ** totalDigits;
const randomInteger = Math.ceil(randomNumberMultiplied);
const randomIndex = randomInteger % totalSentencesCount;
return randomIndex;
}
#getRandomIndexUnique(uniqueUpto = 100) {
if (uniqueUpto > totalSentencesCount)
return new Error(
"This library only supports indices unique upto " + totalSentencesCount
);
let index;
if (this.#recentIndices.length === uniqueUpto) {
this.#recentIndices.unshift();
}
while (!index || this.#recentIndices.includes(index)) {
index = this.#getRandomIndex();
}
this.#recentIndices.push(index);
return index;
}
getRandomSentence(uniqueUpto = 100) {
if (uniqueUpto > totalSentencesCount)
return new Error(
"This library only supports sentences unique upto " +
totalSentencesCount
);
const index = this.#getRandomIndexUnique(uniqueUpto);
return sentences[index].trim();
}
}
const RS = new RandomSentences();
module.exports = RS;