Skip to content

Instantly share code, notes, and snippets.

@Balastrong
Created August 17, 2022 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Balastrong/95998c34d114aee61ca597af98a24398 to your computer and use it in GitHub Desktop.
Save Balastrong/95998c34d114aee61ca597af98a24398 to your computer and use it in GitHub Desktop.
wrand - randomGenerator 2
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