Total Complexity | 7 |
Complexity/F | 3.5 |
Lines of Code | 35 |
Function Count | 2 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | function getRandom(seed) { |
||
2 | let newSeed = 0 |
||
3 | |||
4 | for (let i = 0; i < seed.length; i++) { |
||
5 | newSeed += seed.charCodeAt(i) * Math.pow(10, i) |
||
6 | } |
||
7 | |||
8 | const x = Math.sin(newSeed) * 10000 |
||
9 | return x - Math.floor(x) |
||
10 | } |
||
11 | |||
12 | |||
13 | export default function weightedRandom(weights, randomSeed) { // randomSeed must be a string |
||
14 | if (!randomSeed) { |
||
15 | return -1 |
||
16 | } |
||
17 | |||
18 | let totalWeight = 0 |
||
19 | |||
20 | for (let i = 0; i < weights.length; i++) { |
||
21 | totalWeight += weights[i] |
||
22 | } |
||
23 | |||
24 | let random = getRandom(randomSeed) * totalWeight |
||
25 | |||
26 | for (let i = 0; i < weights.length; i++) { |
||
27 | if (random < weights[i]) { |
||
28 | return i |
||
29 | } |
||
30 | |||
31 | random -= weights[i] |
||
32 | } |
||
33 | |||
34 | return -1 |
||
35 | } |
||
36 |