Refactor choose and weighted

This commit is contained in:
pyoor 2018-09-04 13:34:20 -04:00
parent d09037b37c
commit 7fdbfa84b5

View file

@ -144,43 +144,35 @@ class random {
throw new TypeError(`random.choose() received non-array type: (${list})`)
}
let total = 0
for (let i = 0; i < list.length; i++) {
total += list[i][0]
}
let n = random.number(total)
for (let i = 0; i < list.length; i++) {
if (n < list[i][0]) {
if (flat === true) {
return list[i][1]
} else {
return random.pick([list[i][1]])
}
}
n = n - list[i][0]
const expanded = []
list.forEach(([weight, value]) => {
while (weight--) {
expanded.push(value)
}
})
if (flat) {
return list[0][1]
return random.item(expanded)
}
return random.pick([list[0][1]])
return random.pick(expanded)
}
/**
* More memory-hungry but hopefully faster than random.choose$flat.
* @param {*} wa
* Return a flattened list of weighted values
* [{w: 1, v: 'foo'}, {w: 1, v: 'bar'}]
* @param {Array} list
* @param {Array}
*/
static weighted (wa) {
let a = []
for (let i = 0; i < wa.length; ++i) {
for (let j = 0; j < wa[i].w; ++j) {
a.push(wa[i].v)
}
static weighted (list) {
const expanded = []
list.forEach((item) => {
while (item.w--) {
expanded.push(item.v)
}
})
return a
return expanded
}
static use (obj) {