Skip to content

Test: random string distribution bias #6

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

danielgavrilov
Copy link
Contributor

@danielgavrilov danielgavrilov commented Mar 12, 2025

The random string generator is using a naive method and has a bias. It's probably best to use a library for this (like nanoid) but up to you how you'd like to handle it (I'm not sure if nanoid supports all the environments you need to support).

I have added some (Claude-generated) chi-squared distribution tests to demonstrate the bias (the tests pass when using nanoid).

To switch to nanoid:

pnpm install nanoid
+import { customAlphabet } from "nanoid"
+		return customAlphabet(characterSet)(length);
-
-		const charArray = new Uint8Array(length);
-		getRandomValues(charArray);
-
-		let result = "";
-		for (let i = 0; i < length; i++) {
-			const index = charArray[i] % charSetLength;
-			result += characterSet[index];
-		}
-
-		return result;

@kevlened kevlened mentioned this pull request Apr 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant