probability-picker 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +10 -0
- package/probability-picker.js +68 -0
package/package.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
function probabilityPicker(e) {
|
|
2
|
+
if (e instanceof Object === false) return null;
|
|
3
|
+
let values = Object.entries(e);
|
|
4
|
+
if (values.length === 0) return undefined;
|
|
5
|
+
if (values.length === 1) return values[0][0];
|
|
6
|
+
values = prepareValues(values);
|
|
7
|
+
if (values === undefined) return;
|
|
8
|
+
return chooseOne(values);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function prepareValues(values) {
|
|
12
|
+
values = filterNumbers(values);
|
|
13
|
+
if (values.length === 0) return;
|
|
14
|
+
values = sortValues(values);
|
|
15
|
+
return prepareProbability(values);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function filterNumbers(values) {
|
|
19
|
+
const result = [];
|
|
20
|
+
for (let i = 0; i < values.length; i++) {
|
|
21
|
+
if (typeof values[i][1] === 'number' && !Number.isNaN(values[i][1])) {
|
|
22
|
+
result.push(values[i]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sortValues(values) {
|
|
29
|
+
return values.sort((a, b) => a[1] - b[1]);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function prepareProbability(values) {
|
|
33
|
+
const sum = sumProbabilities(values);
|
|
34
|
+
if (sum === 0) return;
|
|
35
|
+
if (sum === 100) return values;
|
|
36
|
+
return changeProbability(values, sum);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function changeProbability(values, totalProbability) {
|
|
40
|
+
for (let i = 0; i < values.length; i++) {
|
|
41
|
+
values[i][1] = Math.round((values[i][1] / totalProbability) * 100);
|
|
42
|
+
}
|
|
43
|
+
return values;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function sumProbabilities(values) {
|
|
47
|
+
let s = 0;
|
|
48
|
+
for (let i = 0; i < values.length; i++) {
|
|
49
|
+
s += values[i][1];
|
|
50
|
+
}
|
|
51
|
+
return s;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function chooseOne(values) {
|
|
55
|
+
const num = random(1, 100);
|
|
56
|
+
let count = 0;
|
|
57
|
+
for (let i = 0; i < values.length; i++) {
|
|
58
|
+
count += values[i][1];
|
|
59
|
+
if (num <= count) return values[i][0];
|
|
60
|
+
}
|
|
61
|
+
return values;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function random(min, max) {
|
|
65
|
+
return Math.random() * (max - min) + min;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export default probabilityPicker;
|