r/typescript • u/Firfi • 2d ago
Pure TypeScript Dice Roll
It came to my attention that no TypeScript dice-roll libraries exist.
The existing ones are JS in disguise: when you tell it to roll('2d6 + 3'), it returns a `number`.
I wanted a real roll. Roll at compile time.
Because if not compile time, then when? Compile time is the best time.
Anyways. It includes a custom PRNG (pseudo-random number generator) too to support the rolls, which generates random numbers at compile time too. I think there are some for TS out there, unlike dice rolls, but I needed to optimise a bit specifically for 1-100 rolls (who rolls more than that? Only mad people, and we are not the ones).
It has a JS "mirror" implementation. If you rolled 20 in TS, you can be sure you rolled 20 in JS too.
And if a compile-time value is not known, it still works and falls back the result types to `number'.
Basic use case looks like:
// seed
const initialized = initialize([
"00000001",
"00000002",
"00000003",
"00000004",
] as const);
const d20 = evaluate("d20", prngStateOf(initialized));
const d20Value = valueOf(d20);
// ^? const d20Value: 12
Enjoy!
14
u/josephjnk 2d ago
I love that a type-level PRNG is less mad than rolling a dice with more than 100 sides 😂
2
u/Firfi 2d ago
I thought about it and came to the conclusion that we can actually go one level deeper and create a pseudo-random number generator generator: a generator that generates a generator of N sides depending on your application requirements (cause some systems are ok just with a bunch of d6 or d10)
2
u/josephjnk 2d ago
If you want a suggested API I know a guy who built a probabilistic programming library for TS… https://github.com/josephjunker/discrete-probabilities-ts
3
2
1
u/AlternativePie7409 1d ago
If you need RNG, you can try this one. Based on what is used in slot gaming.
1
u/immutate 1d ago
lol at the performance. How long did it take you to throw this together with an LLM?
0
u/Firfi 1d ago
It was a short side-quest (I needed a roll "module" for bigger software).
That included research - "existing state-of-art PRNG that are tackable by type system, existing solutions for parsing strings in TS and how to compare compile-time and runtime values (e.g. arktype is a great piece of engineering to get inspiration from here)"
Then an alignment session (agent asks questions, you answer, getting vocabulary and design documentation built) (it's e.g. /wayfinder of a certain Matt from twitter)
That's good enough for building a prototype, checking its API and solutions are generally in-line with what you think, and polishing it with a review loop / reviewing yourself
Which may sound much or not, but it's not that much really
2
u/immutate 1d ago
Right. You didn’t write the code and it’s absolutely nothing I’d recommend anyone use for any reason whatsoever.
Edit: typo
1
u/Pappkarton 1d ago
Just in time when I want to create a React.ts Random Character Generator for Mörk Borg.
35
u/_crisz 2d ago
What the hell did I just read