-
-
Save Balastrong/95998c34d114aee61ca597af98a24398 to your computer and use it in GitHub Desktop.
wrand - randomGenerator 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class RandomPicker<T> { | |
constructor(private items: WeightedItem<T>[]) { | |
this.updateTotalWeight(); | |
} | |
pick(): T { | |
const random = Math.random() * this.totalWeight; | |
let currentWeight = 0; | |
for (const item of this.items) { | |
currentWeight += item.weight; | |
if (random < currentWeight) { | |
return item.original; | |
} | |
} | |
/* istanbul ignore next */ | |
throw new Error( | |
"No idea why this happened, get in touch with the wrand developer!" | |
); | |
} | |
pickMany(amount: number): T[] { | |
const items = []; | |
for (let i = 0; i < amount; i++) { | |
items.push(this.pick()); | |
} | |
return items; | |
} | |
private updateTotalWeight(): void { | |
this.totalWeight = this.items.reduce((acc, item) => acc + item.weight, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment