Skip to content

Commit

Permalink
stress.{sample, sampleSize}
Browse files Browse the repository at this point in the history
  • Loading branch information
jokester committed May 29, 2024
1 parent 32b5595 commit 828d5f0
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 13 deletions.
13 changes: 0 additions & 13 deletions src/random/number.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
export const defaultRng = Math.random;

function sample<T>(from: ReadonlyArray<T>, count: number, rng = defaultRng): T[] {
const sampled: T[] = from.slice(0, count); // 'reservoir'

for (let i = count; i < from.length; i++) {
const j = Math.floor(1 + Math.random() * i);
if (j < count) {
sampled[j] = from[i];
}
}

return sampled;
}

export function binomialRandom(n: number, p: number, rng = defaultRng): number {
let s = 0;
for (let sample = 0; sample < n; ++sample) {
Expand Down
10 changes: 10 additions & 0 deletions src/stress/__snapshots__/sample.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`sample picks random value: sample([1,2,3]) 1`] = `1`;

exports[`sampleSize picks specified size: sampleSize([1,2,3], 2) 1`] = `
[
1,
2,
]
`;
23 changes: 23 additions & 0 deletions src/stress/sample.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { sample, sampleSize } from './sample';

function fakeRng() {
return 0.3;
}

describe('sample', () => {
it('picks random value', () => {
expect(sample([1, 2, 3], fakeRng)).toMatchSnapshot('sample([1,2,3])');
});
it('returns undefined on empty array', () => {
expect(sample([])).toBeUndefined();
});
});

describe('sampleSize', () => {
it('picks specified size', () => {
expect(sampleSize([1, 2, 3], 2, fakeRng)).toMatchSnapshot('sampleSize([1,2,3], 2)');
});
it('returns undefined on empty array', () => {
expect(sampleSize([2, 3], 3, fakeRng)).toHaveLength(2);
});
});
19 changes: 19 additions & 0 deletions src/stress/sample.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { defaultRng } from '../random/number';

export function sample<T>(input: readonly T[], rng = defaultRng): T {
const index = Math.floor(input.length * rng());
return input[index];
}

export function sampleSize<T>(from: T[], count: number, rng = defaultRng): T[] {
const reservoir: T[] = from.slice(0, Math.min(count, from.length));

for (let i = count; i < from.length; i++) {
const j = Math.floor(1 + Math.random() * i);
if (j < count) {
reservoir[j] = from[i];
}
}

return reservoir;
}

0 comments on commit 828d5f0

Please sign in to comment.