Refactor choose and weighted

This commit is contained in:
pyoor 2018-09-04 13:34:20 -04:00
parent d09037b37c
commit 7fdbfa84b5
1 changed files with 18 additions and 26 deletions

View File

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