Skip to content
Open
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
14 changes: 14 additions & 0 deletions src/user-segmentation-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { generateDeterministicRandomNumber } from './user-segmentation-utils';
import { expect } from '@jest/globals';

describe('user-segmentation-utils', () => {
describe('generateDeterministicRandomNumber', () => {
it('produces uniform distribution across 1000 samples', () => {
const seed = 'some-seed';
const samples = Array(1000).fill(0).map(() => generateDeterministicRandomNumber(seed));
// Use a statistical test for uniformity (e.g. chi-squared test)
const chiSquared = samples.reduce((acc, sample) => acc + Math.pow(sample - 0.5, 2), 0);
expect(chiSquared).toBeLessThan(1000);
});
});
});
10 changes: 10 additions & 0 deletions src/user-segmentation-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { crypto } from 'crypto';

export function generateDeterministicRandomNumber(seed: string): number {
// Use a cryptographically secure pseudo-random number generator (CSPRNG)
const hash = crypto.createHash('sha256');
hash.update(seed);
const randomBytes = hash.digest();
const randomNumber = randomBytes.readUInt32LE(0) / 0xffffffff;
return randomNumber;
}