Completed
Push — master ( 03cb87...68903a )
by Michael
28s queued 12s
created

weightedRandom.js ➔ getRandom   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
dl 0
loc 10
rs 10
c 0
b 0
f 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