Skip to content

Commit

Permalink
fix(random): update weightedRandom()
Browse files Browse the repository at this point in the history
- assume missing weights as zero
  • Loading branch information
postspectacular committed Aug 4, 2021
1 parent f3c65d1 commit 70afa70
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/random/src/weighted-random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { SYSTEM } from "./system";
/**
* Returns a no-arg function which produces a random choice of given weighted
* `choices` and using given {@link IRandom} instance (default {@link SYSTEM}.
* If `weights` are given, it must be the same size as `choices`. If omitted,
* each choice will have same probability.
* If `weights` are given, it must be the same size as `choices` (else missing
* weights will be assumed zero). If omitted entirely, each choice will have
* same probability.
*
* @remarks
* Throws an error if the `choices` array is empty (requires at least 1 item).
Expand All @@ -28,7 +29,7 @@ export const weightedRandom = <T>(
assert(n > 0, "no choices given");
const opts = weights
? choices
.map((x, i) => <[number, T]>[weights[i], x])
.map((x, i) => <[number, T]>[weights[i] || 0, x])
.sort((a, b) => b[0] - a[0])
: choices.map((x) => <[number, T]>[1, x]);
const total = opts.reduce((acc, o) => acc + o[0], 0);
Expand Down

0 comments on commit 70afa70

Please sign in to comment.