Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept empty array in vose #8

Merged
merged 1 commit into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/vose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class Vose {
// from undefined.
throw new Error('Sparse array not allowed');
}
if (tot === 0) {
if ((tot === 0) && (n > 0)) {
throw new Error('Total probability of 0.');
}

Expand Down
16 changes: 8 additions & 8 deletions test/vose.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ import test from 'node:test';
test('vose', () => {
const r = new Random();

throws(() => new Vose([], r), {
message: 'Total probability of 0.',
});
throws(() => new Vose([0, 0, 0], r), {
const v0 = new Vose([]);
ok(v0);

throws(() => new Vose([0, 0, 0]), {
message: 'Total probability of 0.',
});
throws(() => new Vose([-1], r), {
message: 'All probabilities must be non-negative. Got "-1".',
});

const w = [0.1, 1, 10];
const v = new Vose(w, r);
const v = new Vose(w);
ok(v);

const freq = w.map(() => 0);
Expand All @@ -29,15 +29,15 @@ test('vose', () => {
equal(freq.reduce((p, x) => p + x), times);

// 0 probability never picked.
const v2 = new Vose([1, 0, 0], r);
const v2 = new Vose([1, 0, 0]);
for (let i = 0; i < times; i++) {
equal(v2.pick(r), 0);
}

const empty = new Array(1);
empty.push(2);
throws(() => new Vose(empty, r), {message: 'Sparse array not allowed'});
throws(() => new Vose(empty), {message: 'Sparse array not allowed'});
empty[0] = null;
const v4 = new Vose(empty, r);
const v4 = new Vose(empty);
ok(v4);
});